The iota()
function is available in the numeric
header file in C++. iota()
is used to assign successive values of value to every element in a specified range. The value gets incremented by 1 after assignment to an element.
The iota()
method takes the following parameters:
First
: Forward iterator for the initial position of the sequence to be written.Last
: Forward iterator for the final position of the sequence to be written.Value
: Initial value for the accumulator.Forward iterators are iterators that can be used to access the sequence of elements in a range in the direction that goes from its beginning towards its end.
There is no return value.
Let’s understand with the help of an example.
Array = num[16]
Range = [num,num+16) i.e from num[0] to num[15]
Value = 19
We have an array of size = 16, i.e., we can place the elements from index 0 to index 15. For the range, the iota()
function includes the element pointed by first
but excludes the element pointed by last
.
The value in the accumulator is 19, which will get incremented by 1 after every assignment of value to the element until its range is met.
The result of the iota()
function is:
Let’s look at the code snippet.
#include <iostream>#include <numeric>using namespace std;int main(){int num[16];int val;cin >> val;iota(num,num+16,val);cout<<"Elements are: ";for(auto i:num){cout<<' '<<i;}return 0;}
Enter the input below
main
function.int
type.int
type.int
type.iota()
function to assign the sequence of elements in the array.for
loop to access the elements of the array and display them as a result.In this way, we use the iota()
function to generate the sequence of numbers in a specified range.