In C++, std::iota() fills a range with a growing sequence. You give it a start value, and it writes start, start+1, start+2, and so on, until the range is full.
It is the quickest way to make a vector like 1 2 3 4 5 or 0 1 2 3 without a loop. The name comes from the Greek letter ι in the APL language. It works with numbers, characters, and any type that supports ++. Include <numeric> to use it.
This function is declared in the <numeric> header. It exists since C++11. It is a free function, called as std::iota(...), not with a dot.
std::string letters(5, ' ') creates a string of five spaces. These are the five slots to be filled.
The start value is the character 'a'. Each ++ moves to the next letter in the alphabet.
The spaces are replaced by a, b, c, d, e, and the program prints abcde.
Example 3 — Make an Index Array and Sort It by Value
A classic trick: fill indexes with iota(), then sort the indexes instead of the data.
C++
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> v = {30, 10, 20};
std::vector<int> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(),
[&v](int a, int b) { return v[a] < v[b]; });
std::cout << "sorted order of indexes:";
for (int i : idx) {
std::cout << ' ' << i;
}
std::cout << '\n';
return 0;
}
Output
sorted order of indexes: 1 2 0
How It Works
iota() fills idx with 0 1 2. These are the positions of the elements in v.
std::sort() reorders idx with a lambda that compares the valuesv[a] and v[b]. The vector v itself is not moved.
The smallest value 10 sits at index 1, then 20 at index 2, then 30 at index 0. So the indexes end up as 1 2 0.
Frequently Asked Questions
It fills a range with consecutive values. You give a start value, and iota() writes start, start+1, start+2, and so on into the range. It is declared in <numeric>.
Create the vector with size N, then call std::iota(v.begin(), v.end(), 1). For example, std::vector<int> v(10); std::iota(v.begin(), v.end(), 1); gives 1 to 10.
No. It always adds 1 with ++. To get a step of 2, fill with iota() and then change the values, or use std::generate() with your own counter.
iota() only overwrites elements that already exist. An empty vector has none, so nothing happens. Give the vector a size first, for example std::vector<int> v(5).
It comes from the function iota written with the Greek letter ι in the APL language, which makes a list of numbers. The C++ function keeps the name.