C++ Standard Library C++ STL Library

C++ <algorithm> - generate_n() Function



The C++ algorithm::generate_n function is used to assign value returned by successive calls of function gen to the first n elements of the sequence pointed by first.

Syntax

template <class OutputIterator, class Size, class Generator>
  void generate_n (OutputIterator first, 
                   Size n, 
                   Generator gen);
template <class OutputIterator, class Size, class Generator>
  OutputIterator generate_n (OutputIterator first, 
                             Size n, 
                             Generator gen);

Parameters

first Specify initial position of the output iterator.
n Specify number of elements to be assigned.
gen Specify generator function which requires no arguments and returns value which can be assigned in the specified sequence.

Return Value

Returns an iterator pointing to the element that follows the last element whose value has been assigned or None(in C++98).

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::generate_n function is used to assign value in the given sequence 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_n call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //assign values to the vector
  generate_n(vec.begin(), 3, gen);

  cout<<"\nAfter generate_n 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_n call, vec contains: 1 1 1 1 1
After generate_n call, vec contains: 10 20 30 1 1

❮ C++ <algorithm> Library