![]() |
VOOZH | about |
In C++, iota() is a library function used to fill a range of elements with increasing values starting from the given initial value. It assigns the starting value to the first element and then increments it once for the next element and so on.
Let's take a look at an example:
1 2 3 4 5
This article covers the syntax, usage, and common examples of iota() function in C++:
Table of Content
The iota() function is defined inside the <numeric> header file.
iota(first, last, val);
Parameters:
Return Value:
Note: iota() function only works for those STL containers that support random access using index numbers such as vector, deque, etc.
iota() can be used with any range with data types that have a well-defined increment operation (++). The below examples demonstrate the use of iota() with different containers and its behaviour in different conditions.
a b c d e
1 2 3 4 5
Time Complexity: O(n), where n is the number of elements in the given range.
Auxiliary Space: O(1)
Explanation: For iota() to work, the ++ operator must be defined for data type used in the range. So, for custom data type, we need to manually implement the ++ operator as done in struct C.