初始化地图时出错

时间:2016-04-30 12:29:48

标签: c++ dictionary stl

以下代码给出错误“binary'<':找不到运算符,它接受'const point'类型的左手操作数(或者没有可接受的转换)”。我如何修复它?

#include <iostream>
#include <map>
using namespace std;

struct point
{
    float x;
    float y;
public:
    void get() {
        cin >> x >> y;
    }
};

int main()
{
    map<point, point> m;
    point p1, p2;
    p1.get();
    p2.get();
    m.insert(make_pair(p1,p2));
}

1 个答案:

答案 0 :(得分:3)

您必须为<定义point运算符,因为默认情况下std::map会将其用于比较键。

#include <iostream>
#include <map>
using namespace std;

struct point
{
    float x;
    float y;
public:
    // add this function
    bool operator<(const point& p) const {
        // example implementation
        if (x < p.x) return true;
        return x == p.x && y < p.y;
    }
    void get() {
        cin >> x >> y;
    }
};

int main()
{
    map<point, point> m;
    point p1, p2;
    p1.get();
    p2.get();
    m.insert(make_pair(p1,p2));
}

您还可以在std::map的第三个模板参数中指定比较器,但我认为定义<运算符是一种更简单的方法。

相关问题