This C++ program demonstrates the generate_n() algorithm which saves the values generated by a function into a container. The program utilizes the generate_n() algorithm which is slightly different from generate() algorithm where it takes three parameters – pointer to the location where generated values will be saved, the number of values to be generated and the generating function. The generated values are then copied to the std::ostream.
Here is the source code of the C++ program which demonstrates the generate_n() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate the generate_n() Algorithm
*/
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
static int i = 1;
int ret() {
return i++;
}
int main() {
const std::size_t N = 10;
int arr[N];
std::generate_n(arr, N, ret);
std::cout << "arr: ";
std::copy(arr, arr+N, std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
$ gcc test.cpp $ a.out Vector v : 1 2 3 4 5 6 7 8 9 10
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Programming Books
- Check C++ Books
- Apply for C++ Internship
- Apply for Computer Science Internship
- Practice Computer Science MCQs