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?
std::map
takes up to four template type arguments, the third one being a comparator. E.g.:
struct cmpByStringLength {
bool operator()(const std::string& a, const std::string& b) const {
return a.length() < b.length();
}
};
// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
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.