c++qtcompareoperator-overloadingqmultimap

QMultiMap with struct as key and struct as value, comparison operators


I have two structs, for example, first struct as key in QMultiMap:

struct KeyStruct
{
    int keydata1;
    int keydata2;
    int keydata3;
    bool operator < ( const KeyStruct& o ) const
    {
        return keydata1 < o.keydata1 || keydata2 < o.keydata2 || keydata3 < o.keydata3;
    }
};

And second struct as value:

struct ValueStruct
{
    int valuedata1;
    QString valuedata2;
};

I tried to use QMultiMap like this:

multiMap.insert( keyStruct, valueStruct ); // in a loop
foreach( keyStruct, multiMap.keys()){
    foreach( valueStruct, multiMap.values( keyStruct )){
    // it never reaches this line
    }
}

I'm shure in some cases I have multiple values per key, but can't even get one. I think the problem is in comparsion. Also, I tried this:

bool operator == ( const KeyStruct& o ) const
{
    return keydata1 == o.keydata1 &&
           keydata2 == o.keydata2 &&
           keydata3 == o.keydata3;
}

But it seems QMultiMap just doesn't use this code in my case.


Solution

  • Any data structure ( to my knowledge) that requires an operator<() to function has also the condition that:

    A<B => ! B<A
    

    This seems trivial, but in your case, it is possible that A<B && B<A. For instance if A.keydata1 < B.keydata1 but A.keydata2 > B.keydata2.

    To fix this you should write your operator something like this:

     bool operator < ( const KeyStruct& o ) const
    {
        if(keyData1 != o.keyData1) return keyData1 < o.keyData1;
        if(keyData2 != o.keyData2) return keyData2 < o.keyData2;
        //etc
        return false; //they are equal
    
    }