C++ Standard Library C++ STL Library

C++ <algorithm> - generate() Function



The C++ algorithm::generate function is used to assign value returned by successive calls of function gen to elements in the range [first, last).

Syntax

template <class ForwardIterator, class Generator>
  void generate (ForwardIterator first, 
                 ForwardIterator last, 
                 Generator gen);

Parameters

first Specify initial position of the forward iterator. The range used is [first,last).
last Specify final position of the forward iterator. The range used is [first,last).
gen Specify generator function which requires no arguments and returns value which can be assigned in the specified range.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::generate function is used to assign value in the given vector using specified generator function.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; 

int N = 1;
int gen() {
  return 10*(N++);
} 

int main (){
  vector<int> vec{1, 1, 1, 1, 1};
  vector<int>::iterator it;

  cout<<"Before generate call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //assign values to the vector
  generate(vec.begin(), vec.end(), gen);

  cout<<"\nAfter generate call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before generate call, vec contains: 1 1 1 1 1
After generate call, vec contains: 10 20 30 40 50

❮ C++ <algorithm> Library

5