Algorithm Generate N Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Generate N Function

Algorithm Generate N Function

BLUF: Mastering Algorithm Generate N Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Generate N Function

C++ is renowned for its efficiency. Learn how Algorithm Generate N Function enables low-level control and high-performance computing in the tutorial below.

The C++ algorithm generate_n function is employed to assign values generated by a function object to a specified quantity of elements within a range and returns the position just beyond the last assigned value.

The generator function is created by the user and is then repeatedly invoked to assign the numerical values.

Syntax

Example

template <class OutputIterator, class Size, class Generator>
void generate_n (OutputIterator first, Size n, Generator gen);                    //Until C++ 11

template <class OutputIterator, class Size, class Generator>
OutputIterator generate_n (OutputIterator first, Size n, Generator gen);   //Since C++ 11

Parameter

A forward iterator indicating the location of the initial element within the range where values will be assigned.

A function object lacking arguments, employed to produce the values intended for assignment to every element within the range.

n: The number of elements that will be assigned by the generator function can be of either signed or unsigned integer type.

Return value

Complexity

The time complexity is directly proportional to the size of n. It invokes the gen function and carries out an assignment operation for every individual element.

Data races

The initial n elements within the range indicated by the first pointer are altered, with each element undergoing a single modification.

Exception safety

This function raises an exception if any errors occur during the assignment of gen, element, or while performing operations on an iterator.

Please be aware that supplying incorrect parameters can lead to unpredictable behavior.

Example 1

Let's examine a straightforward example to illustrate the functionality of the generate_n function:

Example

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main() {

  int n = 1;
  generate_n(ostream_iterator<int>(cout, ","), 10, [&n]{
        auto t = n; 
        n *= 2; 
        return t;
        });
        
   return 0; 
}

Output:

Output

1,2,4,8,16,32,64,128,256,512,

Example 2

Let's see another simple example:

Example

#include <vector>
#include <deque>
#include <algorithm>
#include <iostream>
#include <ostream>
 
using namespace std;
 
int main()
{
  // 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 ( ), 3 , 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 ( ), 4 , rand );
 
  cout <<"Deque deq1 is ( " ;
  for ( d1_Iter = deq1.begin( ) ; d1_Iter != deq1.end( ) ; d1_Iter++ )
    cout <<*d1_Iter<<" ";
  cout <<")."<<endl;
 
  return 0;
}

Output:

Output

Vector v1 is ( 1804289383 846930886 1681692777 0 0 ).
Deque deq1 is ( 1714636915 1957747793 424238335 719885386 0 ).

Example 3

Let's see another simple example:

Example

#include <iostream> 
#include <vector> 
#include <algorithm> 
  
// Defining the generator function 
int gen() 
{ 
    static int i = 0; 
    return ++i; 
} 
  
using namespace std; 
int main() 
{ 
    int i; 
  
    // Declaring a vector of size 10 
    vector<int> v1(10); 
  
    // using std::generate_n 
    std::generate_n(v1.begin(), 10, gen); 
  
    vector<int>::iterator i1; 
    for (i1 = v1.begin(); i1 != v1.end(); ++i1) { 
        cout << *i1 << " "; 
    } 
    return 0; 
}

Output:

Output

1 2 3 4 5 6 7 8 9 10

Example 4

Let's see another simple example:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::generate_n

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 << '\n';

  return 0;
}

Output:

Output

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

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience