C++ STL algorithm, generate() program  example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

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() to assign the values generated by a function object to each element in a range in C++ programming

To show: How to use the C++ algorithm, generate() to assign the values generated by a function object to each element in a range in C++ programming

 

// C++ STL algorithm, generate()

#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(5);

// vector iterator

vector <int>::iterator Iter1;

// deque container

deque <int> deq(5);

// deque iterator

deque <int>::iterator deqIter;

 

// do the generate() operation

cout<<"\nOperation: generate(vec.begin(), vec.end(), rand)"<<endl;

generate(vec.begin(), vec.end(), 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() operation

cout<<"\nOperation: generate(deq.begin(), deq.end(), rand)"<<endl;

generate(deq.begin(), deq.end(), 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(vec.begin(), vec.end(), rand)

vec vector data: 41 18467 6334 26500 19169

Operation: generate(deq.begin(), deq.end(), rand)

deq deque data: 15724 11478 29358 26962 24464

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index