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

Algorithm Generate Function

BLUF: Mastering Algorithm Generate 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 Function

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

The C++ Algorithm generate function is employed to set the value produced by a function object for each element within a specified range.

The generator function is specified by the user and is invoked repeatedly to assign the numbers.

Syntax

Example

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

Parameter

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

The final element in the range where values are to be assigned is indicated by a forward iterator pointing one position beyond it.

A function object lacking any arguments, utilized to produce the values assigned to each element within the range.

Return value

Complexity

The complexity increases linearly within the specified range [first, last). It invokes the gen function and executes an assignment operation for every element within that range.

Data races

The elements within the range [first, last) undergo modifications, with each element being accessed only once.

Exception safety

This function will raise an exception if any of the assignments to gen, element, or the iterator operation result in an exception.

Please be aware that using incorrect parameters may lead to unpredictable behavior.

Example 1

Let's explore a straightforward example to illustrate the usage of the generate function:

Example

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
  vector<int> v(10);

  int n = 1;
  generate(v.begin(), v.end(), [&n]() { 
      auto t = n; 
      n *= 2; 
      return t; 
      } );

  for_each(v.begin(), v.end(), [](int x) { 
      cout << x << ","; 
      });
  
  return 0;
}

Output:

Output

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

Example 2

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 
    std::generate(v1.begin(), v1.end(), 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 3

Let's see another simple example:

Example

#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 ( v1.begin ( ), v1.end ( ) , 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 ( deq1.begin ( ), deq1.end ( ) , 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 1714636915 1957747793 ).
Deque deq1 is ( 424238335 719885386 1649760492 596516649 1189641421 ).

Example 4

Let's see another simple example:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::generate
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

using namespace std;

// function generator:
int RandomNumber () { return (rand()%100); }

// class generator:
struct c_unique {
  int current;
  c_unique() {current=0;}
  int operator()() {return ++current;}
} UniqueNumber;

int main () {
  srand ( unsigned ( std::time(0) ) );

  vector<int> myvector (8);

  generate (myvector.begin(), myvector.end(), RandomNumber);

  cout << "myvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  generate (myvector.begin(), myvector.end(), UniqueNumber);

  cout << "myvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
   cout << '\n';
 
  return 0;
}

Output:

Output

myvector contains: 93 16 77 25 39 52 56 19
myvector contains: 1 2 3 4 5 6 7 8

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