
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Test Cases in C++
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 −
#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 −
#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