How can I use a struct as key in a std::map?

Try and make operator < const:

bool operator<(const coord &o)  const {

(Your = operator should probably be == operator and const as well)


By far the simplest is to define a global "less than" operator for your struct in stead of as a member function.

std::map uses - by default - the 'lessthan' functor which, in turn, uses the global "operator<" defined for the key type of the map.

bool operator<(const coord& l, const coord& r) {
     return (l.x<r.x || (l.x==r.x && l.y<r.y));
}

As mentioned in the answer by Andrii, you can provide a custom comparison object to the map instead of defining operator< for your struct. Since C++11, you can also use a lambda expression instead of defining a comparison object. Moreover, you don't need to define operator== for your struct to make the map work. As a result, you can keep your struct as short as this:

struct coord {
    int x, y;
};

And the rest of your code could be written as follows:

auto comp = [](const coord& c1, const coord& c2){
    return c1.x < c2.x || (c1.x == c2.x && c1.y < c2.y);
};
std::map<coord, int, decltype(comp)> m(comp);

Code on Ideone

Tags:

C++

C++11

Stdmap