4

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

Resorter
  • 307
  • 3
  • 9

2 Answers2

6

As simple as this:

std::vector<int> v( 123 );
std::iota( std::begin( v ), std::end( v ), 1 );
Slava
  • 43,454
  • 1
  • 47
  • 90
  • Problem here is that you initialize the vector in the first line, and then assign again numbers to it. – mfnx Dec 14 '18 at 11:06
2

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>());
}
skypjack
  • 49,335
  • 19
  • 95
  • 187