C++ STL algorithm, generate_n() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ generate_n() to assign the values generated by a function object to a specified number of element is a range and returns to the position one past the last assigned value in C++ programming

To show: How to use the C++ algorithm, generate_n() to assign the values generated by a function object to a specified number of element is a range and returns to the position one past the last assigned value in C++ programming

// C++ STL algorithm, generate_n()

#include <vector>

#include <deque>

#include <algorithm>

#include <iostream>

using namespace std;

int main(void)

{

// assigning random values to vector integer elements

//

// vector container

vector <int> vec(7);

// vector iterator

vector <int>::iterator Iter1;

// deque container

deque <int> deq(7);

// deque iterator

deque <int>::iterator deqIter;

// do the generate_n() operation

cout<<"\nOperation: generate_n(vec.begin(), 7, rand)"<<endl;

generate_n(vec.begin(), 7, rand);

// print the data

cout<<"vec vector data: ";

for(Iter1 = vec.begin(); Iter1 != vec.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// assigning random values to deque integer elements do the generate_n() operation

cout<<"\nOperation: generate_n(deq.begin(), 4, rand)\n";

generate_n(deq.begin(), 4, rand);

// print the data

cout<<"deq deque data: ";

for(deqIter = deq.begin(); deqIter != deq.end(); deqIter++)

cout<<*deqIter<<" ";

cout<<endl;

return 0;

}

Output examples:

Operation: generate_n(vec.begin(), 7, rand)

vec vector data: 41 18467 6334 26500 19169 15724 11478

Operation: generate_n(deq.begin(), 4, rand)

deq deque data: 29358 26962 24464 5705 0 0 0

Press any key to continue . . .