C++ Reference ยท Algorithms
The std::iota algorithm
Reference for C++ std::iota and ranges::iota: fill a range with consecutive increasing values, index sorting, iterator ranges and the C++23 views::iota.
std::iota (from <numeric>) fills a range with consecutive values. It assigns the starting value to the first element, then repeatedly increments that value with ++ and assigns it to the next element. The name comes from the APL function that creates the sequence 1, 2, 3, ...
It is the usual way to build a list of indices, for example to sort positions by the values stored elsewhere. Because it only needs ++ and assignment, it works with any type that supports them, including iterators, characters and floating-point numbers.
std::vector<int> v(5); std::iota(v.begin(), v.end(), 1); // 1 2 3 4 5
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
template<class FwdIt, class T> constexpr void iota(FwdIt first, FwdIt last, T value); // <numeric>, C++11 // C++23, <numeric> std::ranges::iota(R&& r, T value); std::ranges::iota(O first, S last, T value); // C++20, <ranges> std::views::iota(start); // infinite std::views::iota(start, bound); // [start, bound)
| Name | Description |
|---|---|
first, last |
The range to fill. |
value |
The first value; it is incremented with ++value after each assignment. |
Returns: nothing for std::iota; std::ranges::iota returns a result struct holding the end iterator and the next value.
Errors / undefined behavior: signed integer overflow from the increments is undefined behavior; the destination must hold the whole range.
Usage notes
- Header:
<numeric>, not<algorithm>. Forgetting it is the usual compile error. - Type of the counter:
valueis copied and incremented in its own type, soiota(v.begin(), v.end(), 0)into avector<double>counts withintand converts. Pass0.0to count in doubles. - Step size 1 only. For a different step, use
std::generatewith a lambda, orviews::iota(0, n) | views::transform(...). - Index vectors: the combination
iota+sortwith a comparing lambda gives an "argsort" without moving the data. - Iterators as values: because only
++is required, you can fill a container with iterators or pointers into another one. - Lazy sequences:
std::views::iota(C++20) stores nothing and may be unbounded; combine it withtake,filterandtransform. - Complexity: exactly
last - firstincrements and assignments.