创建一个自己的地图比较器
问题描述:
typedef map<string, string> myMap;
当向myMap插入一个新对时,它将使用键来比较它自己的字符串比较器。
我不知道我们是否可以覆盖那个比较器。
例如比较键的长度,而不是字母表。
或者反正再次对地图排序。
感谢您的帮助。
When inserting a new pair to myMap, it will use the key to compare by its own string comparator. I don't know whether we can override that comparator or not? For example comparing key by its length, not by the alphabet. Or anyway to sort the map again. Thanks for helping.
答
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.