6

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");
Morix Dev
  • 2,700
  • 1
  • 28
  • 49
mario
  • 111
  • 2
  • 3
  • 8

3 Answers3

14

If you find specific key or value you can do something like this:

// Returns 1
int key1 = map.key( "Mario" );

// returns "student"
QString value3 = map.value( 3 );

or do you want to iterate over all items in QMap?

eferion
  • 872
  • 9
  • 14
10

You don't need to iterate over the elements. First get all values via values() and then use contains().

bool ValueExists(const QMap<int, QString> map, const QString valExists) const
{
    return map.contains(valExists);
}
jaques-sam
  • 2,578
  • 1
  • 26
  • 24
Ezee
  • 4,214
  • 1
  • 14
  • 29
  • 1
    This will allocate a temporary container for `map.values()`. Just use `map.contains(valExists);` – jaques-sam Dec 18 '18 at 13:50
  • Regarding the edit to this question: map.values().contains(valueExists) is not the same as map.keys().contains(valueExists). The latter however is equivalent to map.contains(valExists). – Quaternion Nov 03 '21 at 16:49
1

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.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85