std::iota

From cppreference.com
< cpp‎ | algorithm
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Concepts and utilities: std::Sortable, std::projected, ...
Constrained algorithms: std::ranges::copy, std::ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
(C++11)(C++11)(C++11)
(C++17)
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
(C++11)
Binary search operations
Set operations (on sorted ranges)
Heap operations
(C++11)
Minimum/maximum operations
(C++11)
(C++17)
Permutations
Numeric operations
C library
 
Defined in header <numeric>
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );
(since C++11)

Fills the range [first, last) with sequentially increasing values, starting with value and repetitively evaluating ++value.

Equivalent operation:

*(d_first)   = value;
*(d_first+1) = ++value;
*(d_first+2) = ++value;
*(d_first+3) = ++value;
...

Parameters

first, last - the range of elements to fill with sequentially increasing values starting with value
value - initial value to store, the expression ++value must be well-formed

Return value

(none)

Complexity

Exactly last - first increments and assignments.

Possible implementation

template<class ForwardIt, class T>
void iota(ForwardIt first, ForwardIt last, T value)
{
    while(first != last) {
        *first++ = value;
        ++value;
    }
}

Notes

The function is named after the integer function ⍳ from the programming language APL. It was one of the STL components that were not included in C++98, but eventually made it into the standard library in C++11.

Example

The following example applies std::shuffle to a vector of std::list iterators since std::shuffle cannot be applied to a std::list directly. std::iota is used to populate both containers.

#include <algorithm>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector>
 
int main()
{
    std::list<int> l(10);
    std::iota(l.begin(), l.end(), -4);
 
    std::vector<std::list<int>::iterator> v(l.size());
    std::iota(v.begin(), v.end(), l.begin());
 
    std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()});
 
    std::cout << "Contents of the list: ";
    for(auto n: l) std::cout << n << ' ';
    std::cout << '\n';
 
    std::cout << "Contents of the list, shuffled: ";
    for(auto i: v) std::cout << *i << ' ';
    std::cout << '\n';
}

Possible output:

Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5
Contents of the list, shuffled: 0 -1 3 4 -4 1 -2 -3 2 5

See also

copy-assigns the given value to every element in a range
(function template)
assigns the results of successive function calls to every element in a range
(function template)