2016-04-30 118 views
0

以下代码给出了错误“二进制”<':找不到操作符找到'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)); 
} 

回答

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,但我觉得定义<运算符是一个更简单的方法。

+0

为什么我在使用m [p1] = m [p2]而不是m.insert(make_pair(p1,p2))时会出现同样的错误? – user6275035

+0

@ user6275035出于完全相同的原因:因为使用的操作符未定义。 – MikeCAT