C++标准::地图比较方法
C++ std::map compare method
>我在使用以下代码时遇到错误
struct MapKey {
std::string x;
std::string y;
}
std::map<MapKey, int> m;
if (m.find(key) != m.end()) {
......
}
我收到一个错误说,
no match for "operator<" in '__x < __y'
我相信问题是 MapKey 需要有一个比较方法,我想知道如何为 Mapkey 实现一个。例如
struct MapKey {
bool operator<(const MapKey &key) const {
... what shall I put here? ...
}
std::string x;
std::string y;
}
谢谢。
在 MapKey
的定义之后定义它(作为自由函数,而不是成员函数),然后你设置了:
bool operator <(MapKey const& lhs, MapKey const& rhs)
{
return lhs.x < rhs.x || lhs.x == rhs.x && lhs.y < rhs.y;
}
如果定义位于头文件中,请确保将运算符定义为inline
,否则可能会出错链接器。
任何引起严格弱排序的函数(可以接受常量参数)都是可以的。还要记住,你不需要运算符==,但是两个键a和b被认为是等效的,当且仅当!(a
相关文章:
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 比较C++变量的最有效方法
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- 比较"A"、"C"、"G"'T'字符的最快方法
- 任何方法都可以在C++中比较数据结构中的许多方法
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- 在 c++ 中比较不相等数组或字符串的方法
- 使用 lambda 比较初始化优先级队列的方法
- C# 通用比较方法 [C++模板的类似物]
- 比较字符* (C/C++) 的最快方法?
- 获取字符串大小的各种方法之间的比较
- C 是否具有对两个STD :: sets,vectors等进行三角比较的标准方法
- 比较两个文件中的两个中间人的最佳方法.C++
- sort() 方法 c++ 中的比较器函数.为大量数字获得不同的解决方案
- 比较数据库搜索方法
- C++ 将整数与硬编码的整数集进行比较的更简单方法
- C++方法与Java的比较(从Java到C ++的语法)
- 正确的方法比较两个指向算法中使用的指向算法