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

半世苍凉 提交于 2019-12-03 09:33:54

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

Another solution, which may be used for third-party data types, is to pass a Comparison object as third template parameter. example

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!