pickzy.com

C  |  C++  |  Objective-C  |  VC++  |  Win32  |  MFC  |  Java  |  Php  |  Delphi  |  Visual Basic  |  .Net  |  Networking  |  General  |  Games  |  Jobs  |  Javascript  |  




Menu

pickSourcecode.com


        

 




 

Cpp > Programs

 

cpp unary_function example and tutorials

#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
#include <algorithm>
using namespace std;


const 
int VectorSize = 5;

template<class T>

class Print: public unary_function<T, 
void>
{

public:

void operator()(T& arg1)
{

cout << arg1 << " ";

}

};


template<class T>

class GreaterThanTwo: public unary_function<T, bool>

{

public:

bool operator()(T& arg1)

{

return (arg1 > 2);

}

};


template<class Container, class Iterator>

void ShowElement(Container& c, Iterator& itor);

int main()
{

Print<int> DoPrint;

vector<int> vInt(VectorSize);

typedef vector<int>::iterator Itor;


for (int i = 0; i < VectorSize; ++i)
vInt[i] = i;


Itor first = vInt.begin();

Itor last = vInt.end();


cout << "
for_each()\n";
for_each(first, last, DoPrint);
cout << "\n";


Itor retItor = find(first, last, 2);

cout << "find(first, last, 2) = ";

ShowElement(vInt, retItor);

cout << "\n";


retItor = find(first, last, 10);

cout << "find(first, last, 10) = ";

ShowElement(vInt, retItor);

cout << "\n";


GreaterThanTwo<int> IsGreaterThanTwo;

retItor = find_
if(first, last, IsGreaterThanTwo);
cout << "find(first, last, IsGreaterThanTwo) = ";

ShowElement(vInt, retItor);

cout << "\n";


int retSize = count(first, last, 3);
cout << "count(first, last, 3) = " << retSize << "\n";


retSize = count_
if(first, last, IsGreaterThanTwo);
cout << "count_
if(first, last, IsGreaterThanTwo) = " << retSize << "\n";

return 0;

}


template<class Container, class Iterator>

void ShowElement(Container& c, Iterator& itor)
{

if (itor != c.end())
cout << *itor;

else

cout << "last";

}



 
Privacy Policy | About Us