C ++ std :: map比较方法

时间:2012-04-07 00:48:13

标签: c++ map std

我遇到以下代码错误

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;
}

感谢。

2 个答案:

答案 0 :(得分:9)

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

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

如果定义在头文件中,请确保将运算符定义为inline,否则会冒链接器错误。

答案 1 :(得分:2)

任何诱导strict weak ordering的函数(可以采用const参数)都可以。还要记住你不需要算子==,但是当且仅当!(a&lt; b)&amp;&amp; !(b&lt; a)。