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

后端 未结 4 571
攒了一身酷
攒了一身酷 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: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 m(comp);
    

    Code on Ideone

提交回复
热议问题