iota: Initialize a C++ container with increasing values

satyam1203

Satyam Lachhwani

Posted on February 15, 2021

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.push_back(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.

Use

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 -

Github
LinkedIn

💖 💪 🙅 🚩
satyam1203
Satyam Lachhwani

Posted on February 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related