如何为地图创建自己的比较器?
typedef map<string, string> myMap;
当向 myMap
插入新对时,它将使用键 string
通过自己的字符串比较器进行比较。是否可以覆盖该比较器?例如,我想按密钥 string
的长度进行比较,而不是按字母表进行比较。或者还有其他方法可以对地图进行排序吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::map
最多需要四个模板类型参数,第三个是比较器。 例如:或者,您也可以将比较器传递给
map
的构造函数。但请注意,当按长度进行比较时,映射中每个长度只能有一个字符串作为键。
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.
自 C++11 起,您还可以使用 lambda 表达式 而不是定义比较器结构:
输出:
我想重复 Georg 答案的最后一条注释:按长度比较时,地图中每个长度只能有一个字符串作为键。
Ideone 上的代码
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
是的,
map
上的第三个模板参数指定比较器,它是一个二元谓词。例子:Yes, the 3rd template parameter on
map
specifies the comparator, which is a binary predicate. Example:将比较函数的指针类型指定为映射中的第三种类型,并将函数指针提供给映射构造函数:
map; mapName(pointerToComparisonFunction);
看一下下面的示例,为
map
提供比较函数,以vector
迭代器为键,int< /code> 作为值。
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a
map
, withvector
iterator as key andint
as value.