How to find specific value in Qmap
Asked Answered
N

3

7

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");
Nipissing answered 9/9, 2014 at 15:53 Comment(0)
Z
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.

Zilpah answered 9/9, 2014 at 16:27 Comment(0)
P
16

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?

Preprandial answered 9/9, 2014 at 16:2 Comment(0)
V
11

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);
}
Veljkov answered 10/9, 2014 at 6:50 Comment(2)
This will allocate a temporary container for map.values(). Just use map.contains(valExists);Tews
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).Boo
Z
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.

Zilpah answered 9/9, 2014 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.