QMultiHash, several same keys?



  • Hello.

    I'm doing a program that manage multiple Serial Ports. Every serial port is associated to multiples windows.

    For manage this task, i,'ve thought in a hash, with serial port as key, and windows as values. I've implemented and works.

    But there is a problem. When i get the keys with function keys() return multiple times the sames keys. For example in this code:

        QString* m5 = new QString("Is multiple of 5");
        QString* m5cpy = new QString("Is multiple of 5");
        int a = 10;
        int b = 20;
        QMultiHash<QString*, int> hash_table;
        hash_table.insert(m5, a);
        hash_table.insert(m5, 8);
        hash_table.insert(m5cpy, b);
        printf("Values[");
        QList<int> v = hash_table.values(m5);
        for(int i=0; i<v.length();i++){
            printf("%i,", v[i]);
        }
        printf("]\n");
        printf("Num keys=%i\n", hash_table.keys().length());
        printf("[");
        for(int i=0; i<hash_table.keys().length();i++){
            printf("%p, ",hash_table.keys()[i]);
        }
        printf("]\n");
    

    Ooutput is:
    Values[8,10, ]
    num keys=3
    [0000000000237CB0, 0000000000237CB0, 0000000000237CD0, ]

    Call to values() works, return all values associated to same key(m5 and m5cpy are diferent, although have same content). But there are multiple keys for m5??? I'm doing something wrong or i need redefine some function to calculate hash or something?



  • Nothing too complicated, you are just using the wrong method to retrieve the keys, use uniqueKeys.

    hash_table.keys().length() will always be ==hash_table.values().length() which is useful in certain situations, if you just want the non-duplicate keys use the appropriate method



  • Wow thanks, i don't see this method. It's what I was looking for.

    Thanks.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.