5

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

5
  • 4
    check out std::iota Commented Oct 7, 2016 at 18:48
  • Take a look at std::initializer_list Commented Oct 7, 2016 at 18:51
  • @krzaq Huh what please? Commented Oct 7, 2016 at 18:51
  • 3
    @πάνταῥεῖ 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 Commented Oct 7, 2016 at 18:53
  • Possible duplicate of How to initialize a vector in c++ Commented Oct 7, 2016 at 19:15

2 Answers 2

6

As simple as this:

std::vector<int> v( 123 ); std::iota( std::begin( v ), std::end( v ), 1 ); 
Sign up to request clarification or add additional context in comments.

1 Comment

Problem here is that you initialize the vector in the first line, and then assign again numbers to it.
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>()); } 

1 Comment

Wouldn't that (realistically) result in huge .rodata section?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.