The iota function is included in the numeric header file of C++. Every element inside a given range of values is given a new value using the iota function . After an assignment to an element, the value of the element is increased by 1 by default. In this article, we will discuss about the iota function with its syntax, parameters, and examples.
Syntax:
It has the following syntax:
void iota (ForwardIterator first, ForwardIterator last, T val);
Syntax parameters:
The following parameters are passed to the iota method :
First:
A forward iterator is used to the initial position of the series to be written.
Last:
The forward iterator is used to write the final point of the sequence.
Value:
It represents the initial value of the accumulator.
Note: Forward iterators are those that can access a range's sequence of elements in the direction that runs from its start to its finish.
Return value
No return value is present.
Example
Let's take an example to understand this function in C++.
Array = num[15]
Range = [num,num+15) i.e from num[0] to num[14]
Value = 19
We can place the elements from index 0 to index 14 in our array because it is size = 15 , which is 15 . Iota includes the elemencpp tutorialed by first but excludes the elemencpp tutorialed by last for the range.
The accumulator currently has a value of 19 , which will increase by 1 after each time a value is assigned to an element until its range is reached.
The iota function's output is:
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
Example: 1
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int num[15];
int val;
cin>>val;
iota(num,num+16,val);
cout<<"Elements are: ";
for(auto i:num)
{
cout<<' '<<i;
}
return 0;
}
Output:
12
Elements are: 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Working mechanism:
- First, we import the needed header files in lines 1 and 2 .
- After that, we create a main function in line 4 .
- Line 6 contains the declaration of an int type array.
- A variable of the int type is declared in line 7.
- Line 8 is where the input of type int is taken.
- The array's element order is assigned using the iota method in line 9.
- We show a notification regarding the future outcome in line 10.
- Now, the for loop is used in lines 11 through 14 to retrieve the array's items and show them as a result.
- It is how we generate a series of numbers within a given range using the iota function .
Example: 2
// C++ program to illustrate iota()
#include <iostream>
#include <numeric>
int main()
{
int numbers[12];
// Initialising starting value as 200
int st = 200;
std::iota(numbers, numbers + 12, st);
std::cout<< "Elements are :";
for (auto i : numbers)
std::cout<< ' ' <<i;
std::cout<< '\n';
return 0;
}
Output:
Elements are : 200 201 202 203 204 205 206 207 208 209 210 211