C ++ std :: map comparison method

I ran into an 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 am getting the error:

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

      

I believe the problem is that MapKey must have a comparison method, I am wondering how I can implement it for Mapkey. For example,

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

      

Thank.

+3


source to share


2 answers


Define this after definition MapKey

(as a free function, not a member function) and you set:

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

      



Be sure to define the statement as inline

if the definition is in the header file, otherwise you risk linker errors.

+9


source


Any function (which can take const arguments) that invokes strict weak ordering in order. Also remember that you don't need the == operator, but the two keys a and b are considered equivalent if and only if! (A <b) && &! (b <a).



+2


source







All Articles