We need a flexible compare way for our objects in some situations, so it’s necessary to write our own compare class.
The article has an example which puts all widgets in a multiset container, the widgets should be sort by its data member Speed
. The widgets are created with random number that will be assgined to variable Speed.
The details are displayed in the following code.
#include <iostream>
#include <string>
#include <numeric>
#include <set>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Widget
{
int GetSpeed() const { return speed; }
Widget( const int _speed ){ this->speed = _speed; }
int speed;
};
class WidgetCompare: public binary_function<Widget, Widget, bool>
{
public:
bool operator()( const Widget &leftW, const Widget &rightW ) const
{
return leftW.GetSpeed() < rightW.GetSpeed();
}
};
int Random( int limit )
{
return static_cast<int>( 1.0 * rand() / RAND_MAX * limit + 0.5 );
}
int main()
{
multiset<Widget, WidgetCompare> widgets;
srand( time( nullptr ) );
for( int i = 0; i < 10; ++i )
{
widgets.insert( Widget( Random(10) ) );
}
for( auto it: widgets )
{
cout << it.GetSpeed() << " ";
}
cout << endl;
return 0;
}
/*
4 4 4 6 7 7 8 8 9 10
*/
The binary_function
is declared as struct in C plus plus header file __funtional_base
. It’s ok to create class or struct that inherits it.
Because there are only a few differences between struct and class:
- it gets access-specifier
public
when the drived class is declared asstruct
or it gets access-specifierprivate
if programmer didn’t give a explicit access-specifier. - The members in class are private defaultly. The members in struct or union are public defaultly.
For the function Random
, its parameter limit means that the biggest number it created is equal to value limit
.