Namespaces
Variants
Views
Actions

std::generate

From cppreference.com
< cpp‎ | algorithm
Revision as of 08:50, 10 January 2013 by Radix (Talk | contribs)

 
 
 

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

<td>
Defined in header <algorithm>
</td>

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

<td class="t-dcl-nopad">
template< class ForwardIt, class Generator >
void generate( ForwardIt first, ForwardIt last, Generator g );
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Assigns each element in range [first, last) a value generated by the given function object g.

Contents

Parameters

first, last - the range of elements to generate
g - generator function object that will be called.

The signature of the function should be equivalent to the following:

Ret fun();

The type Ret must be such that an object of type ForwardIt can be dereferenced and assigned a value of type Ret. ​

Type requirements
-
ForwardIt must meet the requirements of ForwardIterator.

Return value

(none)

Complexity

Exactly std::distance(first, last) invocations of g() and assignments.

Possible implementation

template<class ForwardIt, class Generator>
void generate(ForwardIt first, ForwardIt last, Generator g)
{
    while (first != last) {
        *first++ = g();
    }
}

Example

The following code fills a vector with random numbers:

#include <algorithm>
#include <iostream>
#include <cstdlib>
 
int main()
{
    std::vector<int> v(5);
    std::generate(v.begin(), v.end(), std::rand); // Using the C function rand()
 
    std::cout << "v: ";
    for (auto iv: v) {
        std::cout << iv << " ";
    }
    std::cout << "\n";
}

Possible output:

v: 52894 15984720 41513563 41346135 51451456

See also

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