Namespaces
Variants
Views
Actions

std::iota

From cppreference.com
< cpp‎ | algorithm
Revision as of 19:37, 2 November 2012 by P12bot (Talk | contribs)

 
 
 

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <numeric>
</td>

<td></td> <td></td> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class ForwardIterator, class T >
void iota( ForwardIterator first, ForwardIterator last, T value );
</td>

<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end

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;
...

Contents

Parameters

first, last - the range of elements to sum
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 ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value)
{
    while(first != last) {
        *first++ = value;
        ++value;
    }
}

Example

The following example applies std::random_shuffle to a vector of iterators to a std::list since std::random_shuffle cannot be applied to an std::list directly. std::iota is used to create the vector.

#include <numeric>
#include <algorithm>
#include <list>
#include <vector>
#include <iostream>
 
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::random_shuffle(v.begin(), v.end());
 
    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';
}

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

Template:cpp/algorithm/dcl list fillTemplate:cpp/algorithm/dcl list generate