< cpp‎ | algorithm
Revision as of 09:50, 10 January 2013 by Radix (Talk | contribs)

Algorithm library
Execution policies (C++17)
Non-modifying sequence operations
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
Binary search operations
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations

Numeric operations
C library

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

Defined in header <algorithm>

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

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

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



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



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();


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