如何使用QHash::removeIf(Predicate Pred)

How to use QHash::removeIf(Predicate Pred)

Qt 6.1 introduced the method removeIf(Predicate Pred) 其数 collection 类: QByteArray, QHash, QList, QMap, QMultiHashQMultiMapQStringQVarLengthArray.

但是我该如何写谓词呢?

让我们举一个QHash例子:

struct MishMash {
    int i;
    double d;
    QString str;
    enum Status { Inactive=0, Starting, Going, Stopping };
    Status status;
};

QHash<QString, MishMash> myHash;

// ... fill myHash with key-value pairs

// Now remove elements where myHash[key].status == MishMash::Status::Inactive;
myHash.removeIf(???);

来自文档...

The function supports predicates which take either an argument of type QHash<Key, T>::iterator, or an argument of type std::pair<const Key &, T &>.

既然如此,您应该能够使用 lambda 类似(未测试)...

myHash.removeIf(
    [](QHash<QString, MishMash>::iterator i)
    {
        return i.value().status == MishMash::Status::Inactive;
    }
);