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.
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.
;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With