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
}
}
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
}
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With