Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.


Assigns the values generated by a function object to a specified number of elements in a range and returns to the position one past the last assigned value.

template<class OutputIterator, class Diff, class Generator>
   void generate_n(
      OutputIterator _First, 
      Diff _Count, 
      Generator _Gen


An output iterator addressing the position of first element in the range to which values are to be assigned.


A signed or unsigned integer type specifying the number of elements to be assigned a value by the generator function.


A function object that is called with no arguments that is used to generate the values to be assigned to each of the elements in the range.

The function object is invoked for each element in the range and does not need to return the same value each time it is called. It may, for example, read from a file or refer to and modify a local state. The generator's result type must be convertible to the value type of the forward iterators for the range.

The range referenced must be valid; all pointers must be dereferenceable and, within the sequence, the last position must be reachable from the first by incrementation.

The complexity is linear, with exactly _Count calls to the generator being required.

generate_n has two related forms:

For information on how these functions behave, see Checked Iterators.

// alg_generate_n.cpp
// compile with: /EHsc
#include <vector>
#include <deque>
#include <algorithm>
#include <iostream>
#include <ostream>

int main() {
   using namespace std;

   // Assigning random values to vector integer elements
   vector <int> v1 ( 5 );
   vector <int>::iterator Iter1;
   deque <int> deq1 ( 5 );
   deque <int>::iterator d1_Iter;
   generate_n ( v1.begin ( ), 5 , rand );
   cout << "Vector v1 is ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   // Assigning random values to deque integer elements
   generate_n ( deq1.begin ( ), 3 , rand );

   cout << "Deque deq1 is ( " ;
   for ( d1_Iter = deq1.begin( ) ; d1_Iter != deq1.end( ) ; d1_Iter++ )
      cout << *d1_Iter << " ";
   cout << ")." << endl;

Vector v1 is ( 41 18467 6334 26500 19169 ).
Deque deq1 is ( 15724 11478 29358 0 0 ).

Header: <algorithm>

Namespace: std

Community Additions

© 2016 Microsoft