Driven class of `unary_function` can be used to check a single element based on special condition.
Programmer can regard it as some algorithms’ parameter, such as `count_if`, `find_if`, and `find_if_not`.
The following code shows how to write a customized unray class and use it.
C++
``````struct Widget
{
int GetSpeed() const { return speed; }
Widget( const int _speed ){ this->speed = _speed; }
int speed;
};

class EvenNumber: public unary_function<Widget, bool>
{
public:
bool operator()( Widget &w )
{
return ( (w.GetSpeed() & 1) == 0 );
}
};

int main()
{
vector<Widget> widgets;
for( int i = 0; i < 6; ++i )
{
widgets.push_back( Widget( i ) );
}
cout << "The count of event number is " << count_if( widgets.begin(), widgets.end(), EvenNumber() ) << endl;

auto it = find_if( widgets.begin(), widgets.end(), EvenNumber() );
cout << "The first event number is " << it->GetSpeed() << endl;

cout << "All even numbers are: " << endl;
for_each( widgets.begin(), widgets.end(),
[]( Widget &w ){ if( EvenNumber().operator()( w )  )  cout << w.GetSpeed() << " "; } );
cout << endl;
return 0;
}
/*
The count of event number is 3
The first event number is 0
All even numbers are:
0 2 4
*/``````
It’s better to use the STL algorithm than writing a program loop to deal with the logic judge in the above example. Because we can get higher quality code, there are fewer code statements in a source file, and readers can understand what the program is doing by the name of the STL algorithm easily.
Categories: AlgorithmCPlusPlus

0 0 vote
Article Rating
Subscribe
Notify of 