qtqhash

Partial key matching QHash


I have a QHash defined as follows

QHash<QString, QString> hashLookup;

I have inserted a few values to this hash as follows:

hashLookup.insert("OMG", "Oh my God!");
hashLookup.insert("LOL", "Laugh out loud");
hashLookup.insert("RIP", "Rest in peace");
// and so on

I have a few QStrings as follows:

QString a = "OMG_1";
QString b = "LOL_A";
QStirng c = "OMG_YOU";
QString d = "RIP_two";

I am supposed to find if these values exist in hashLookup, i.e, since OMG_1 contains OMG, I should be able to retrieve Oh my God!.

I have tried to do this using

if(hashLookup.contains(a)
//do something

which ofcourse tries to look for a key OMG which is not present in the lookup table and does not return anything. Is partial matching of key values possible in Qt? If yes, how should I go about implementing this.


Solution

  • There is no opportunity in QHash class to extract values by partial matching of key, because QHash use hash function (Qt documentation: qHash) which:

    The qHash() function computes a numeric value based on a key. It can use any algorithm imaginable, as long as it always returns the same value if given the same argument. In other words, if e1 == e2, then qHash(e1) == qHash(e2) must hold as well. However, to obtain good performance, the qHash() function should attempt to return different hash values for different keys to the largest extent possible.

    Different keys give almost always different hash.

    In your task you can run on QHash keys and make comparison with QString functionality. Something like this:

    QString getHashValue(const QString& strKey, const QHash<QString, QString>& hashLookup)
    {
        QList<QString> uniqueKeys = hashLookup.uniqueKeys();
        foreach(const QString& key, uniqueKeys)
        {
            if(strKey.contains(key))
                return hashLookup.value(key);
        }
    }
    

    ...

    getHashValue("OMG_1", hashLookup);