C++ std :: map比较方法

260*_*607 3 c++ std map

我遇到了以下代码的错误

struct MapKey {
    std::string x;
    std::string y;
}

std::map<MapKey, int> m;

if (m.find(key) != m.end()) {
    ......
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说,

no match for "operator<" in '__x < __y'
Run Code Online (Sandbox Code Playgroud)

我相信问题是MapKey需要有一个比较方法,我想知道如何为Mapkey实现一个.例如,

struct MapKey {
    bool operator<(const MapKey &key) const {
        ... what shall I put here? ...
    }
    std::string x;
    std::string y;
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

ild*_*arn 9

在定义之后MapKey定义它(作为自由函数,而不是成员函数)并且你设置了:

bool operator <(MapKey const& lhs, MapKey const& rhs)
{
    return lhs.x < rhs.x || lhs.x == rhs.x && lhs.y < rhs.y;
}
Run Code Online (Sandbox Code Playgroud)

确保将运算符inline定义为定义位于头文件中,否则会冒链接器错误.