如何为地图创建自己的比较器? [英] How can I create my own comparator for a map?

查看:65
本文介绍了如何为地图创建自己的比较器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

或者,您也可以将比较器传递给 map s构造函数

Alternatively you could also pass a comparator to maps constructor.

但是请注意则按长度比较时,在地图中每个长度只能有一个字符串作为键。

Note however that when comparing by length you can only have one string of each length in the map as a key.

这篇关于如何为地图创建自己的比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆