问题描述
typedef map<string, string> myMap;
在 myMap
中插入新对时,它将使用键 string
通过自己的字符串比较器进行比较。是否可以覆盖该比较器?例如,我想比较键 string
的长度,而不是字母。还是有其他方法可以对地图进行排序?
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
最多包含四个模板类型参数,第三个是比较器。例如:
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.
这篇关于如何为地图创建自己的比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!