I want to map objects of a given class to objects of another. The class I want to use as key, however, was not written by me and is a simple struct with a few values. std::map orders it’s contents, and I was wondering how it does it, and if any arbitrary class can be used as a key or if there’s a set of requirements (operators and what not) that need to be defined.
If so, I could create a wrapper for the class implementing the operators map uses. I just need to know what I need to implement first, and none of the references for the class I found online specify them.
All that is required of the key is that it be copiable and assignable.
The ordering within the map is defined by the third argument to the
template (and the argument to the constructor, if used). This
defaults to
std::less<KeyType>, which defaults to the<operator,but there’s no requirement to use the defaults. Just write a comparison
operator (preferably as a functional object):
Note that it must define a strict ordering, i.e. if
CmpMyType()( a, breturns true, then)
CmpMyType()( b, a )must return false, and ifboth return false, the elements are considered equal (members of the
same equivalence class).