Suppose n is a large integer, how to initialize a vector with {1,2,...,n} without a loop in C++? Thanks.
Asked
Active
Viewed 4,001 times
4
-
4check out `std::iota` – krzaq Oct 07 '16 at 18:48
-
Take a look at [`std::initializer_list`](http://en.cppreference.com/w/cpp/utility/initializer_list) – πάντα ῥεῖ Oct 07 '16 at 18:51
-
@krzaq Huh what please? – πάντα ῥεῖ Oct 07 '16 at 18:51
-
2@πάνταῥεῖ You can use `iota` to fill a sequence with incrementing values. It certainly looks like a better solution than an initializer list when *n is a large integer* – krzaq Oct 07 '16 at 18:53
-
Possible duplicate of [How to initialize a vector in c++](http://stackoverflow.com/questions/8906545/how-to-initialize-a-vector-in-c) – Sensei James Oct 07 '16 at 19:15
2 Answers
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