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

后端 未结 4 550
攒了一身酷
攒了一身酷 2020-12-09 16:00

I have the following code, but I get an error on on the last line:

struct coord { 
    int x, y; 

    bool operator=(const coord &o) {
        return x          


        
相关标签:
4条回答
  • 2020-12-09 16:05

    Try and make operator < const:

    bool operator<(const coord &o)  const {
    

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

    0 讨论(0)
  • 2020-12-09 16:09

    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));
    }
    
    0 讨论(0)
  • 2020-12-09 16:12

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

    0 讨论(0)
  • 2020-12-09 16:22

    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

    0 讨论(0)
提交回复
热议问题