Reputation: 1945
I have a std::map that contains 3 elements, and I'm trying to to see if a key exists in the map. I have put the map through the debugger, and it contains all 3 elements added to it. When using find it stops after the first element and immediatley returns map.end()... I even made sure to override the operator< in the key. Anyone have a clue why find is stopping after the first key?
Here is the operator< for the key:
bool MyClass::operator<(const MyClass& myClass) const
{
bool aIsEqual = a == myClass.a || a == "0" || myClass.a == "0";
bool bIsEqual = b == myClass.b || b == "0" || myClass.b == "0";
bool cIsEqual = c == myClass.c || c == "0" || myClass.c == "0";
return !aIsEqual || !bIsEqual || !cIsEqual;
}
Upvotes: 1
Views: 187
Reputation: 347
std::map
is one of the associative containers as defined in section 23.2.4 of the standard.
There are resctrictions you have to keep in mind while implementing the operator<
or Compare
object for these containers:
- Each associative container is parameterized on
Key
and an ordering relationCompare
that induces a strict weak ordering ( 25.4 ) on elements ofKey
. (...)- The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys
k1
andk2
are considered to be equivalent if for the comparison objectcomp
,comp(k1, k2) == false && comp(k2, k1) == false
. For any two keysk1
andk2
in the same container, callingcomp(k1, k2)
shall always return the same value.
In your case you failed to meet these conditions (e.g. the ordering), hence the "bad" behaviour of the map.
Upvotes: 1
Reputation: 595412
Without knowing exactly what your a
, b,
and c
members actually represent, I can only guess, but I would think your operator should probably look something more like this instead:
bool MyClass::operator<(const MyClass& myClass) const
{
if ((a < myClass.a) || ((a == "0") && (myClass.a != "0")))
return true;
if (a == myClass.a)
{
if ((b < myClass.b) || ((b == "0") && (myClass.b != "0")))
return true;
if (b == myClass.b)
return ((c < myClass.c) || ((c == "0") && (myClass.c != "0")));
}
return false;
}
Upvotes: 0