I\'m wondering why I can\'t use STL maps with user-defined classes. When I compile the code below, I get the following cryptic error message. What does it mean? Also, why is
The right solution is to Specialize std::less
for your class/Struct.
• Basically maps in cpp are implemented as Binary Search Trees.
For each node, node.left.key < node.key < node.right.key
Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.
In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .
So It means keys should be compatible with std::less
or operator<
so that they can be organized. Please check map parameters.
Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.
Solution : Specialize std::less
:
The third parameter in map template is optional and it is std::less
which will delegate to operator<
,
So create a new std::less
for your user defined data type. Now this new std::less
will be picked by std::map
by default.
namespace std
{
template<> struct less<MyClass>
{
bool operator() (const MyClass& lhs, const MyClass& rhs) const
{
return lhs.anyMemen < rhs.age;
}
};
}
Note: You need to create specialized std::less
for every user defined data type(if you want to use that data type as key for cpp maps).
Bad Solution:
Overloading operator<
for your user defined data type.
This solution will also work but its very bad as operator <
will be overloaded universally for your data type/class. which is undesirable in client scenarios.
Please check answer Pavel Minaev's answer