DEV Community

Cover image for iota: Initialize a C++ container with increasing values
Satyam Lachhwani
Satyam Lachhwani

Posted on

iota: Initialize a C++ container with increasing values

In C++, when we want to initialize a container(say vector) with increasing values, we tend to use for loop to insert values like this:

vector<int> array;
for(int i = 0; i < 10; i++) {
// array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

To achieve the same thing, we can use a function defined in the C++ Algorithm library, let's first see it in action before going into details:

vector<int> array(10);
iota(array.begin(), array.begin() + 10, 0);
// array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

See, how easy it becomes to initialize a container with sequential values starting from any integer. Let's now move forward and know more about this function.


Include the required header file in order to be able to use the iota function. You can either include bits/stdc++.h or include algorithm and numeric on the top of your .cpp file.

Accepted function parameters

  1. Starting address of the container
  2. Address up to which the container needs to be filled with sequential values
  3. Initial value to be assigned (after which it is auto-incremented and assigned)

Note: This function doesn't return anything.

Things to keep in mind

  • The array must be initialized with some size before using this function.
  • The second parameter (last address up to which values are filled) should not exceed the ending address of the container.
  • We can use array.end() as the second parameter for filling the whole container
  • We can pass either an integer variable or a constant (as done in the above snippet)

For full reference, visit here

If you find anything wrong or if you know some more exciting functions or other stuff related to C++, please drop a comment below so we learn together.

My Profile -


Top comments (2)

pgradot profile image
Pierre Gradot

I always forget about this function... Thanks for the reminder!

The header to include is <numeric>, as indicated by cppreference. Other headers probably happen to include in your compiler and there is a chance that other compilers won't agree.

std::generate is also great (and std::iota can be implemented with std::generate). See

satyam1203 profile image
Satyam Lachhwani

Thanks, Good to know about generate