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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With