2

I use QHash as a container and I have a task to remove all items that satisfy the predicate. At first I thought to use the Erase-remove idiom it turned out that QHash has no option to delete the range, but only a function to delete a single element through the iterator.

std::unordered_map (which is conceptually close to the Qt's QHash) has the function of removing the range.

This implies a question: why QHash does not have a similar function and how to the best way remove items from the QHash satisfying the predicate?

4

2 に答える 2

1

コメントに基づいて、erase-remove イディオムは QHash コンテナーには適用されないことがわかりました。

したがって、 QHash::eraseの説明を考えると、特にハッシュ内のアイテムの順序に違反しないということです

remove() や take() とは異なり、この関数によって QHash が内部データ構造を再ハッシュすることはありません。これは、反復中に安全に呼び出すことができ、ハッシュ内のアイテムの順序に影響を与えないことを意味します。

述語を満たす要素を削除する次のコードがあります。

for( auto it = hash.begin(); it != hash.end(); )
{
    if( pred(*it) )
    {
        it = hash.erase(it); 
    } else {
        ++it;
    }
}
于 2014-09-10T10:58:18.377 に答える