0

I have the below snippet which is acting as a predicate for the sort function. This is for sorting the value pair in a hash map which i have put in a vector. The sort is getting called on a vector

  struct val_less : binary_function<pair<string, unsigned int>, pair<string, unsigned int>,     bool>
{
    bool operator() ( pair<string, unsigned int>&x , pair<string, unsigned int> &y )
    const {

        return x.second>y.second;
    }


}val_gt;

I understand what the code is doing, but i do not understand why it is being done so. What is the binary_function and why do we need to use it as ":". what is the operator() function and why is it bool operator (). I understand the reference parameters as we want to change back the original vector.

Thanks

user775093
  • 699
  • 2
  • 11
  • 22
  • 1
    See http://stackoverflow.com/questions/609937/what-is-the-benefit-of-inheriting-from-stdbinary-function-or-stdunary-funct for a start. – Mark Ransom Mar 09 '14 at 02:40

1 Answers1

0

The binary_function is a base class for your sorting function:

http://www.cplusplus.com/reference/functional/binary_function/

The syntax:

struct val_less : binary_function<pair<string, unsigned int>, pair<string, unsigned int>,     bool>

indicates that your structure is a derivative of the template instantiation of binary_function. The ":" denotes the inheritance.

Moreover, the structure works as a functor type in C++ - the operator() is overridden and the sort function will use it for comparison. This usage of functors can be replaced by anonymous functions in C++11.

mcopik
  • 341
  • 2
  • 6