2607
2607

Reputation: 4115

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.

Upvotes: 3

Views: 5755

Answers (2)

Cosyn
Cosyn

Reputation: 4987

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

Upvotes: 2

ildjarn
ildjarn

Reputation: 62975

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.

Upvotes: 9

Related Questions