Read this question about how to compare custom objects in C++.
I did not understand the operator overloading used here. What is the operator being overloaded here? Is it ()? What is the use of overloading that?
struct MyStruct
{
int key;
std::string stringValue;
MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};
struct less_than_key
{
inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
{
return (struct1.key < struct2.key);
}
};
The point is to use a
less_than_keyobject as a function:Object that can be called like functions (including garden variety functions) are sometimes called functors (warning: this is not the meaning of functor in mathematics), or function objects, or sometimes functoids.
Many standard library algorithms and containers expect such function objects as arguments. For instance,
std::mapcan be customized with a binary function object (exactly like the one you showed us) to know how it should sort the keys.Please refer to this beginners’ book list and read about standard algorithms and containers to understand where you can use those beasts.
Function objects and iterators are the core of the C++ standard library, you should really learn about them to make the best use of C++.