Resorter
Resorter

Reputation: 317

In C++ how to initialize a vector with values {1,2,...,n} without a loop?

Suppose n is a large integer, how to initialize a vector with {1,2,...,n} without a loop in C++? Thanks.

Upvotes: 5

Views: 4246

Answers (2)

skypjack
skypjack

Reputation: 50540

If N is known at compile-time, you can define an helper function like this:

#include<utility>
#include<vector>

template<std::size_t... I>
auto gen(std::index_sequence<I...>) {
    return std::vector<std::size_t>{ I... };
}

int main() {
    auto vec = gen(std::make_index_sequence<3>());
}

Upvotes: 2

Slava
Slava

Reputation: 44238

As simple as this:

std::vector<int> v( 123 );
std::iota( std::begin( v ), std::end( v ), 1 );

Upvotes: 6

Related Questions