Last Updated : 04 Jun, 2025
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:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v(5);
// Assign increasing values starting from 1
iota(v.begin(), v.end(), 1);
for (auto i : v)
cout << i << " ";
return 0;
}
This article covers the syntax, usage, and common examples of iota() function in C++:
Syntax of iota()The iota() function is defined inside the <numeric> header file.
iota(first, last, val);
Parameters:
Return Value:
Examples of iota()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.
Initializing Array Elements using iota() C++
#include <bits/stdc++.h>
using namespace std;
int main() {
char arr[5];
int n = sizeof(arr)/sizeof(arr[0]);
// Assigning arr elements with sequentially
// increasing values starting from 'a'
iota(arr, arr + n, 'a');
for (auto i : arr)
cout << i << " ";
return 0;
}
Using iota with Custom Data Types C++
#include <bits/stdc++.h>
using namespace std;
struct C {
int a;
// Defining ++ for struct C
C& operator++() {
++a;
return *this;
}
};
int main() {
vector<C> v(5);
// Fill the vector starting from Counter{1}
iota(v.begin(), v.end(), C{1});
for (auto i: v) {
cout << i.a << " ";
}
return 0;
}
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4