Another C++ STL function object 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: -

To do: Printing integers using the C++ STL function object in C++ programming

To show: Another function object C++ STL program example demonstrating printing integers

 

// another C++ function object example

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

 

// simple function object that prints the passed arguments

class PrintSomething

{

public:

void operator() (int elem) const

{

cout<<elem<<' ';

}

};

 

int main(void)

{

// vector container

vector<int> vec;

 

// insert elements from 1 to 10

cout<<"Inserting integers from 1 to 10 using push_back()..."<<endl<<endl;

for(int i=1; i<=10; ++i)

vec.push_back(i);

// print all the elements

cout<<"Printing the elements"<<endl;

for_each(vec.begin(), vec.end(), // range

PrintSomething()); // operation

cout<<endl;

return 0;

}

 

Output example:

 

Inserting integers from 1 to 10 using push_back()...

Printing the elements

1 2 3 4 5 6 7 8 9 10

Press any key to continue . . .

 

 

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