Suppose n is a large integer, how to initialize a vector with {1,2,...,n} without a loop in C++? Thanks.
2 Answers
As simple as this:
std::vector<int> v( 123 ); std::iota( std::begin( v ), std::end( v ), 1 ); 1 Comment
mfnx
Problem here is that you initialize the vector in the first line, and then assign again numbers to it.
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>()); } 1 Comment
krzaq
Wouldn't that (realistically) result in huge .rodata section?
std::iotastd::initializer_listiotato fill a sequence with incrementing values. It certainly looks like a better solution than an initializer list when n is a large integer