Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::map compare method

I ran into error with the following code

struct MapKey {
    std::string x;
    std::string y;
}

std::map<MapKey, int> m;

if (m.find(key) != m.end()) {
    ......
}

I receive an error says,

no match for "operator<" in '__x < __y'

I believe the problem is that MapKey needs to have a compare method, I am wondering how can I implement one for Mapkey. For example,

struct MapKey {
    bool operator<(const MapKey &key) const {
        ... what shall I put here? ...
    }
    std::string x;
    std::string y;
}

Thanks.

like image 373
2607 Avatar asked Aug 21 '26 13:08

2607


1 Answers

Define this after MapKey's definition (as a free function, not a member function) and you're set:

bool operator <(MapKey const& lhs, MapKey const& rhs)
{
    return lhs.x < rhs.x || lhs.x == rhs.x && lhs.y < rhs.y;
}

Make sure to define the operator as inline if the definition is in a header file, otherwise you risk linker errors.

like image 112
ildjarn Avatar answered Aug 23 '26 02:08

ildjarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!