generate() and generate_n() functions in C++

In this tutorial, we will be learning the working of generate() and generate_n() functions in C++. These two functions are defined in std::algorithm header and are used to generate test cases for arrays. We will see how we can do this further in this tutorial.

generate() function in C++

The syntax for generate() function is given here:

void generate (ForwardIterator first, ForwardIterator last, Generator generator_function);

In the above syntax, first and last are the Forward iterators to first and last positions respectively. And generator_function is a generator function that is used in generating numbers. Since for test cases we need random numbers, we will be using the rand generator function in the below example program.

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <algorithm>

using namespace std; 

int main()
{
  srand(time(0));
  
  vector<int> vec(10);
  
  generate(vec.begin(), vec.end(), rand);
  
  cout << "Generated elements are:\n";
  for(int i=0; i<10; i++)
    cout << vec[i] << endl;
    
  return 0;
}

Output:

Generated elements are:
540
23781
13295
3542
25471
30484
660
16774
971
5472

In the above example program, we have first included all the required headers. We have used rand() as the generator function in generate() function generates random numbers for the test cases. srand(time(0)) has been used so that the system generates a different set of random numbers for every execution. If we don’t use the srand statement, we will get the same set of random every time we execute the program. We can also create our own generator function and pass it to the generate() function.

generate_n() in C++

This function does the same task as the generate function. The only difference is that in generate() function the second argument is the Forward Iterator to the last position whereas in generate_n() function it is the number of values that are to be generated. See the given example program. That will clear any misunderstanding or doubt.

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <algorithm>

using namespace std; 

int main()
{
  srand(time(0));
  
  vector<int> vec(10);
  
  generate_n(vec.begin(), 10, rand);
  
  cout << "Generated elements are:\n";
  for(int i=0; i<10; i++)
    cout << vec[i] << endl;
    
  return 0;
}

Output:

Generated elements are:
38
7719
21238
2437
8855
11797
8365
32285
10450
30612

Thank you.

Also read: std::fill() and std::fill_n() functions in C++

Leave a Reply

Your email address will not be published. Required fields are marked *