Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Numeric::iota() function



The C++ std::numeric::iota() function is used to fill a range of elements with sequentially increasing values. It takes three arguments, the beginning iterator, end iterator and the starting value. It starts from the provided value and increments it for each subsequent element in the range.

Syntax

Following is the syntax for std::numeric::iota() function.

void iota (ForwardIterator first, ForwardIterator last, T val);

Parameters

  • first, last − It indicate the iterators to the initial and final positions in a sequence.
  • val − It is an initial value for the accumulator.

Return Value

none

Exceptions

It throws if any of the assignments or increments throws.

Data races

The elements in the range [first1,last1) are accessed.

Example 1

In the following example, we are going to consider the basic usage of the iota() function.

#include <iostream>
#include <numeric>
#include <array>
int main() {
   std::array < int, 4 > a;
   std::iota(a.begin(), a.end(), 1);
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

Output

Output of the above code is as follows −

1 2 3 4 

Example 2

Consider the following example, we are going to fill the array with even numbers.

#include <iostream>
#include <numeric>
#include <vector>
int main() {
   std::vector < int > a(4);
   std::iota(a.begin(), a.end(), 0);
   for (int & x: a) {
      x *= 2;
   }
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

0 2 4 6

Example 3

Let's look at the following example, where we are going to fill it with the negative values.

#include <iostream>
#include <numeric>
#include <list>
int main() {
   std::list < int > a(4);
   std::iota(a.begin(), a.end(), -4);
   for (int x: a) {
      std::cout << x << " ";
   }
   return 0;
}

Output

Following is the output of the above code −

-4 -3 -2 -1
numeric.htm
Advertisements