function template

std::generate_n

<algorithm>
template <class OutputIterator, class Size, class Generator>
  void generate_n ( OutputIterator first, Size n, Generator gen );
Generate values for sequence with function
Sets the value of the first n elements in the sequence pointed by first to the value returned by successive calls to gen.

The behavior of this function template is equivalent to:
1
2
3
4
5
template <class OutputIterator, class Size, class Generator>
  void generate_n ( OutputIterator first, Size n, Generator gen )
{
  for (; n>0; --n)  *first++ = gen();
}


Parameters

first
Output iterators to the initial positions in a sequence of at least n elements.
n
Number of elements to set value to.
Its type is an integral type or some other type convertible to it.
gen
Generator function that takes no arguments and returns some value to be stored as element value. This can either be a pointer to a function or an object whose class overloads operator().

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
// generate_n example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int current(0);
int UniqueNumber () { return ++current; }

int main () {
  int myarray[9];

  generate_n (myarray, 9, UniqueNumber);

  cout << "myarray contains:";
  for (int i=0; i<9; ++i)
    cout << " " << myarray[i];

  cout << endl;
  return 0;
}


A possible output:
myarray contains: 1 2 3 4 5 6 7 8 9

Complexity

Linear: Invokes gen and assigns that value, n times.

See also