Search code examples
c++qtqmap

How to find specific value in Qmap


I need to know in QMap second value there is. Functions like first() and last() are useless. Do i have to use iterator, some kind of loop?

 QMap<int, QString> map;
 map.insert(1, "Mario");
 map.insert(2, "Ples");
 map.insert(3, "student");
 map.insert(4, "grrr");

Solution

  • A map provides quick access based upon the key (the first argument).

    So, yes, if you want to know if a value exists (the second argument), you would need to iterate over the map values:-

    bool ValueExists(const QMap<int, QString> map, const QString valExists)
    {
        QList<QString> valuesList = map.values(); // get a list of all the values
        foreach(QString value, valuesList)
        {
            if(value == valExists)
            {
                return true;
            }
        }
        return false;
    } 
    

    To simplify the code, we can also use the values' contains() method, which internally will iterate over the values, as above.