Freedom_Ben
Freedom_Ben

Reputation: 11933

How to iterate over all values() in a QMultiHash

I need to iterate over a QMultiHash and examine the list of values that correspond to each key. I need to use a mutable iterator so I can delete items from the hash if they meet certain criteria. The documentation does not explain how to access all of the values, just the first one. Additionally, the API only offers a value() method. How do I get all of the values for a particular key?

This is what I'm trying to do:

QMutableHashIterator<Key, Value*> iter( _myMultiHash );
while( iter.hasNext() )
{
    QList<Value*> list = iter.values();  // there is no values() method, only value()
    foreach( Value *val, list )
    {
        // call iter.remove() if one of the values meets the criteria
    }
}

Upvotes: 6

Views: 6014

Answers (3)

fghj
fghj

Reputation: 9394

May be better to use recent documentation: http://doc.qt.io/qt-4.8/qmultihash.html

In particular:

QMultiHash<QString, int>::iterator i = hash1.find("plenty");
 while (i != hash1.end() && i.key() == "plenty") {
     std::cout << i.value() << std::endl;
     ++i;
 }

Upvotes: 2

Nicolas Dusart
Nicolas Dusart

Reputation: 2007

You can iterate over all values of a QMultiHash as in a simple QHash:

for(auto item = _myMultiHash.begin(); item != _myMultiHash.end(); item++) {
  std::cout << item.key() << ": " << item.value() << std::endl;
}

It is just that the same key may appear several times if there are multiple values using the same key.

Upvotes: 2

Freedom_Ben
Freedom_Ben

Reputation: 11933

For future travelers, this is what I ended up doing so as to continue use of the Java style iterators:

QMutableHashIterator<Key, Value*> iter( _myMultiHash );
while( iter.hasNext() )
{
    // This has the same effect as a .values(), just isn't as elegant
    QList<Value*> list = _myMultiHash.values( iter.next().key() );  
    foreach( Value *val, list )
    {
        // call iter.remove() if one of the values meets the criteria
    }
}

Upvotes: 3

Related Questions