The iota function is a part of the numeric header file in C++. It assigns new values to each element within a specified range. By default, the value of each element is incremented by 1 after assignment. This guide will explore the iota function, covering its syntax, parameters, and providing examples.
Syntax:
It has the following syntax:
void iota (ForwardIterator first, ForwardIterator last, T val);
Syntax parameters:
The iota method receives the parameters listed below:
First:
A forward iterator is employed to indicate the starting position of the sequence to be outputted.
Last:
The forward iterator is employed to designate the last element in the sequence.
Value:
It signifies the starting 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 consider an example to comprehend this function in C++.
Array = num[15]
Range = [num,num+15) i.e from num[0] to num[14]
Value = 19
We have the flexibility to store elements in the array starting from index 0 up to index 14 since the array size is 15. The iota function populates the elements beginning from the first element but stops before reaching the last element within the specified range.
The accumulator is presently set at 19 and will increment by 1 with each assignment to an element until it reaches its specified range.
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