如何迭代QMultiHash中的所有值()

How to iterate over all values() in a QMultiHash

本文关键字:QMultiHash 迭代 何迭代      更新时间:2023-10-16

我需要对QMultiHash进行迭代,并检查与每个键对应的值列表。我需要使用可变迭代器,这样我就可以在满足某些条件的情况下从哈希中删除项目。文档没有解释如何访问所有值,只解释了第一个值。此外,API仅提供value()方法。如何获取特定密钥的所有值?

这就是我要做的:

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
    }
}

对于未来的旅行者来说,为了继续使用Java风格的迭代器,我最终会这样做:

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
    }
}

最好使用最新的文档:http://doc.qt.io/qt-4.8/qmultihash.html

特别是:

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

您可以像在简单的QHash:中一样迭代QMultiHash的所有值

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

只是如果有多个值使用同一个键,那么同一个密钥可能会出现多次。