Generating Test Cases (generate() and generate_n() in C++

C++Server Side ProgrammingProgramming

In this section we will see how we can use C++ STL function to generate test cases. Sometimes generating test cases for array programs can be very complicated and inefficient process. C++ provides two methods to generate test cases. These methods are as follows −

The generate() method

The C++ function std::algorithm::generate() assigns the value returned by successive calls to gen to the elements in the range of first to last. It takes three parameters first, last and gen, these are forward iterator to the initial position, backward iterator to the final position and generator function that is called with no argument, and return values.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int create_random() {
   return (rand() % 1000);
}
int main () {
   srand(time(NULL));
   vector<int> data(15);
   generate(data.begin(), data.end(), create_random);
   for (int i=0; i<data.size(); i++)
      cout << data[i] << " " ;
}

Output

449 180 785 629 547 912 581 520 534 778 670 302 345 965 107

The generate_n() method

The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen for first n elements. It takes three parameters first, n and gen, these are forward iterator to the initial position, number of calls will be there and generator function that is called with no argument, and return values.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int create_random() {
   return (rand() % 1000);
}
int main () {
   srand(time(NULL));
   vector<int> data(15);
   generate_n(data.begin(), 6, create_random);
   for (int i=0; i<data.size(); i++)
      cout << data[i] << " " ;
}

Output

540 744 814 771 254 913 0 0 0 0 0 0 0 0 0
raja
Published on 27-Aug-2020 17:13:14
Advertisements