This post will discuss how to initialize a vector with a sequential range 1 to n in C++.

1. Using std::iota

The std::iota function assigns consecutive values to every element in the specified range. It can be used as follows to fill a vector with successive values starting from 1 till n.

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

2. Using Loop

Another viable alternative is to use a regular for-loop to fill the array with sequential range 1 to n. This is demonstrated below:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

3. Using std::generate_n

We can also use the std::generate_n function to generate successive values by repeatedly calling a generator function. This can be implemented as follows in C++.

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9 10

4. Using Boost

Fianlly, we can use C++ boost library to fill up a vector with the numbers 0 through n with boost::counting_iterator. The only iterator operation missing from built-in integer types is operator*(), which returns the current value of the integer. The counting iterator adaptor adds this to whatever type it wraps.

Download Code

Output:

1 2 3 4 5 6 7 8 9 10

 
To fill an existing vector, use std::copy.

Download Code

Output:

1 2 3 4 5 6 7 8 9 10

That’s all about initializing a vector with a sequential range 1 to n in C++.