I’m using an STL map with a struct for a key. This is the definition of the map:
std::map<Coord2<uint8_t>, MapTile> tile_;
The definition of the struct:
template <typename T>
struct Coord2
{
T x;
T y;
bool operator<(const Coord2<T> &coord) const { return (x < coord.x || y < coord.y); }
bool operator>(const Coord2<T> &coord) const { return (x > coord.x || y > coord.y); }
}
Will I experience issues with the map because the comparison?
This
operator<is unsuitable for use with the C++ Standard Library’s associative containers.A comparator must provide a strict weak ordering, which yours does not. Consider the following operands that demonstrate its inconsistency:
Given these inputs,
a < b == trueandb < a == true, butb != a.A correct comparison for this type might be:
(It’s certainly possible to write this correct code in a more compact fashion, however I’ve debugged enough errors caused by incorrectly implemented strict weak orderings that I’d strongly recommend being very explicit in the comparison so that it is clear that it is correct. With this implementation, it is very clear that we only compare the
yvalues if thexvalues compare equal, which is what we want.)