typedef map<string, string> myMap;
When inserting a new pair to myMap
, it will use the key string
to compare by its own string comparator. Is it possible to override that comparator? For example, I'd like to compare the key string
by its length, not by the alphabet. Or is there any other way to sort the map?
Since C++11, you can also use a lambda expression instead of defining a comparator struct:
Output:
I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.
Code on Ideone
Yes, the 3rd template parameter on
map
specifies the comparator, which is a binary predicate. Example:std::map
takes up to four template type arguments, the third one being a comparator. E.g.:Alternatively you could also pass a comparator to
map
s constructor.Note however that when comparing by length you can only have one string of each length in the map as a key.