Generating Test Cases (generate() and generate_n() in C++)
Generating test cases for array programs can be a cumbersome process. But the generate and generate_n functions in the STL (Standard Template Library), come handy to populate the array with random values.
- generate()
The generate functions assigns random values provided by calling the generator function ‘gen’ to the elements in the range [begin, end). Notice that begin is included in the range but end is NOT included.
Following code demonstrates the implementation of generate :
#include <bits/stdc++.h>
using namespace std;
int randomize()
{
return ( rand () % 1000);
}
int main ()
{
srand ( time (NULL));
vector< int > vect(10);
generate(vect.begin(), vect.end(), randomize);
for ( int i=0; i<vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Output :
832 60 417 710 487 260 920 803 576 58
NOTE : The output would be different each time we run the code because of srand. If we remove srand, we would get the same set of random numbers every time we run the code.
- generate_n()
The generate_n does the same job as generate upto n elements starting from the element pointed to by the begin iterator.
The following code demonstrates the working of generate_n :
#include <bits/stdc++.h>
using namespace std;
int randomize()
{
return ( rand () % 1000);
}
int main ()
{
srand ( time (NULL));
vector< int > vect(10);
generate_n(vect.begin(), 6, randomize);
for ( int i=0; i<vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Output :
177 567 15 922 527 4 0 0 0 0
NOTE : Here also, the output would be different each time we run the code because of srand. If we remove srand, we would get the same set of random numbers every time we run the code.
Last Updated :
29 May, 2017
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...