0

Qt 6.1 introduced the method removeIf(Predicate Pred) to a number of its collection classes: QByteArray, QHash, QList, QMap, QMultiHash, QMultiMap, QString and QVarLengthArray.

But how do I write a predicate?

Let's take a QHash example:

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(???);
Paul Masri-Stone
  • 2,843
  • 3
  • 29
  • 51
  • From the [documentation](https://doc.qt.io/qt-6/qhash.html#removeIf): `The function supports predicates which take either an argument of type QHash::iterator, or an argument of type std::pair`. have you tried either of those? – G.M. May 24 '22 at 11:43
  • I read this in the documentation. Although I'm familiar with iterators for looping through a collection, I don't understand how to formulate that as a Predicate argument with the match condition. And I cannot find any examples when I've searched. – Paul Masri-Stone May 24 '22 at 11:48

1 Answers1

1

From the documentation...

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 &>.

That being the case, you should be able to use a lambda something along the lines of (untested)...

myHash.removeIf(
    [](QHash<QString, MishMash>::iterator i)
    {
        return i.value().status == MishMash::Status::Inactive;
    }
);
G.M.
  • 12,232
  • 2
  • 15
  • 18