0

The following code gives error "binary '<': no operator found which takes a left-hand operand of type 'const point' (or there is no acceptable conversion)" .How can I fix it ?

#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));
}
user6275035
  • 91
  • 2
  • 9

1 Answers1

3

You have to define < operator for point because std::map uses it for comparison of keys by default.

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

You can also specify a comparator in the third template parameter for std::map, but I think defining < operator is an easier way.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70