Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this program overloading () operator?

Tags:

c++

set

stl

Currently I am studying Standard Template Library (STL).

In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place).

Code :

#include <iostream>
#include <set>
#include <functional>

using namespace std;

class UnitLess
{
public:
    bool operator()(long first, long second)
    {
        long fu = first % 10;
        long su = second % 10;

        return fu < su;
    }
};

typedef set<long, UnitLess> Ctnr;

int main(void)
{
    Ctnr store;

    store.insert(3124);
    store.insert(5236);
    store.insert(2347);
    store.insert(6415);
    store.insert(4548);
    store.insert(6415);

    for(Ctnr::iterator i = store.begin(); i != store.end(); ++i)
    {
        cout << *i << endl;
    }
}

But I don't understand why our Professor has overloaded () operator ?

Thanks.

like image 903
Searock Avatar asked Dec 05 '22 01:12

Searock


1 Answers

The class's purpose is to implement a function that sorts the elements in the set in a given way. This is known as a predicate.

It is implemented as a functor, i.e. by allowing the function operator to be used on an object (this is what std::set does beneath the hood). Doing so is the common way for STL and similar code to call custom objects. (A function pointer is more limited than a function object (a.k.a. functor)

So it's used like this:

Unitless functor;

functor(123, 124); // returns true or false

std::set is a sorted binary tree, so it calls the Unitless's ()-operator several times on each insert to determine where each long value should go.

Try compiling and putting some printf/std::cout in there and see what happens.

Also, be aware that callbacks like this (i.e. when you can't see the call to your code) are scary and confusing in the beginning of your learning curve.

  • Then you get used to it and use them all over, because they are neat.
  • Then your code gets scary and confusing again and you avoid them like the plague.
  • Then you become a duct-tape programmer and use them only where appropriate, but never elsewhere.

;)

like image 181
Macke Avatar answered Dec 18 '22 03:12

Macke