I have a class where I overload all the comparison operators. I load a bunch of these objects into a map as keys and I expect the map to sort them least to greatest.
However, the map is actually sorted by greatest to least. Why is this? Does it not use the comparison operators on the key when it sorts the map? How can I make it do this?
If you look at the definition for std::map, the 3rd parameter is the comparator –
std::less< Key >by default. The default implementation of which is just to invokeoperator<.You could try defining a new version in the header where
YourTypeis defined, like so:Remember to friend
std::less< YourType >in your class.The actual test must comply with the following or you’ll get all kinds of problems:
One important thing to note (that I discovered quite recently) is that if your compiler starts complaining that you’ve redefined the meaning of
std::lessor other funky things, it could be that you’ve only forward declared yourYourTypewhen you declared yourstd::map< YourType >.Hope this helps!