C++标准::地图比较方法

C++ std::map compare method

本文关键字:方法 比较 地图 C++ 标准      更新时间:2023-10-16

>我在使用以下代码时遇到错误

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