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 a random number that will be assigned to the 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>
    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 a struct in CPP 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:
1. it gets access-specifier public when the driven class is declared as struct or it gets access-specifier private if the programmer didn’t give an explicit access-specifier.
2. The members in the class are private by default. The members of struct or union are public by default.
For the function Random, its parameter limit means that the biggest number it created is equal to the value limit.


Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page