简体   繁体   中英

std::map.find() stopping at first element?

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;
}

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:

  1. Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering ( 25.4 ) on elements of Key . (...)
  2. The phrase “equivalence of keys” means the equivalence relation imposed by the comparison and not the operator== on keys. That is, two keys k1 and k2 are considered to be equivalent if for the comparison object comp , comp(k1, k2) == false && comp(k2, k1) == false . For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.

In your case you failed to meet these conditions (eg the ordering), hence the "bad" behaviour of the map.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM