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:

  1. it gets access-specifier public when the drived class is declared as struct or it gets access-specifier private if programmer didn’t give a explicit access-specifier.
  2. 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.


0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Content Summary
: Input your strings, the tool can get a brief summary of the content for you.

X
0
Would love your thoughts, please comment.x
()
x