function template
<algorithm>

std::generate

template <class ForwardIterator, class Generator>
  void generate (ForwardIterator first, ForwardIterator last, Generator gen);
Generate values for range with function
Assigns the value returned by successive calls to gen to the elements in the range [first,last).

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
template <class ForwardIterator, class Generator>
  void generate ( ForwardIterator first, ForwardIterator last, Generator gen )
{
  while (first != last) {
    *first = gen();
    ++first;
  }
}


Parameters

first, last
Forward iterators to the initial and final positions in a sequence. The range affected is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
gen
Generator function that is called with no arguments and returns some value of a type convertible to those pointed by the iterators.
This can either be a function pointer or a function object.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// generate algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::generate
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

// function generator:
int RandomNumber () { return (std::rand()%100); }

// class generator:
struct c_unique {
  int current;
  c_unique() {current=0;}
  int operator()() {return ++current;}
} UniqueNumber;

int main () {
  std::srand ( unsigned ( std::time(0) ) );

  std::vector<int> myvector (8);

  generate (myvector.begin(), myvector.end(), RandomNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  std::generate (myvector.begin(), myvector.end(), UniqueNumber);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
 
  return 0;
}


A possible output:
myvector contains: 57 87 76 66 85 54 17 15
myvector contains: 1 2 3 4 5 6 7 8

Complexity

Linear in the distance between first and last: Calls gen and performs an assignment for each element.

Data races

The objects in the range [first,last) are modified (each object is accessed exactly once).

Exceptions

Throws if any of gen, the element assignments or the operations on iterators throws.
Note that invalid arguments cause undefined behavior.

See also