Utils: Add "findOr(..., nullopt, ...)" function

findOr(nullopt) returns either a value or a std::nullopt for the first entry
in a container where the predicate returned true.

This makes it easy to write constructs like:

if (auto found = Utils::findOr(container, std::nullopt, [](auto){ ... condition ...}) {
...
}

Change-Id: I6f8f0f9c0d8486c32395123d8c2dcba427887189
Reviewed-by: Eike Ziller <eike.ziller@qt.io>
This commit is contained in:
Marcus Tillmanns
2023-11-29 11:00:54 +01:00
parent 4153520fb6
commit 0e59c9e4e1
2 changed files with 22 additions and 0 deletions

View File

@@ -476,6 +476,9 @@ void tst_Algorithm::findOr()
std::vector<int> v1{1, 2, 3, 4};
QCOMPARE(Utils::findOr(v1, 10, [](int i) { return i == 2; }), 2);
QCOMPARE(Utils::findOr(v1, 10, [](int i) { return i == 5; }), 10);
QCOMPARE(Utils::findOr(v1, std::nullopt, [](int i) { return i == 5; }), std::nullopt);
QCOMPARE(Utils::findOr(v1, std::nullopt, [](int i) { return i == 3; }), 3);
}
void tst_Algorithm::findOrDefault()