Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 287
Freedom_Ben Avatar asked Jul 05 '13 22:07

Freedom_Ben


3 Answers

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
    }
}
like image 62
Freedom_Ben Avatar answered Sep 29 '22 16:09

Freedom_Ben


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;
 }
like image 41
fghj Avatar answered Sep 29 '22 15:09

fghj


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.

like image 36
Nicolas Dusart Avatar answered Sep 29 '22 14:09

Nicolas Dusart