forked from qt-creator/qt-creator
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:
@@ -82,6 +82,10 @@ template<typename T, typename R, typename S>
|
|||||||
Q_REQUIRED_RESULT typename T::value_type findOr(const T &container,
|
Q_REQUIRED_RESULT typename T::value_type findOr(const T &container,
|
||||||
typename T::value_type other,
|
typename T::value_type other,
|
||||||
R S::*member);
|
R S::*member);
|
||||||
|
template<typename T, typename F>
|
||||||
|
Q_REQUIRED_RESULT std::optional<typename T::value_type> findOr(const T &container,
|
||||||
|
std::nullopt_t,
|
||||||
|
F function);
|
||||||
|
|
||||||
/////////////////////////
|
/////////////////////////
|
||||||
// findOrDefault
|
// findOrDefault
|
||||||
@@ -473,6 +477,21 @@ typename T::value_type findOr(const T &container, typename T::value_type other,
|
|||||||
return findOr(container, other, std::mem_fn(member));
|
return findOr(container, other, std::mem_fn(member));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template<typename C, typename F>
|
||||||
|
Q_REQUIRED_RESULT typename std::optional<typename C::value_type> findOr(const C &container,
|
||||||
|
std::nullopt_t,
|
||||||
|
F function)
|
||||||
|
{
|
||||||
|
typename C::const_iterator begin = std::begin(container);
|
||||||
|
typename C::const_iterator end = std::end(container);
|
||||||
|
|
||||||
|
typename C::const_iterator it = std::find_if(begin, end, function);
|
||||||
|
if (it == end)
|
||||||
|
return std::nullopt;
|
||||||
|
|
||||||
|
return *it;
|
||||||
|
}
|
||||||
|
|
||||||
//////////////////
|
//////////////////
|
||||||
// findOrDefault
|
// findOrDefault
|
||||||
//////////////////
|
//////////////////
|
||||||
|
|||||||
@@ -476,6 +476,9 @@ void tst_Algorithm::findOr()
|
|||||||
std::vector<int> v1{1, 2, 3, 4};
|
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 == 2; }), 2);
|
||||||
QCOMPARE(Utils::findOr(v1, 10, [](int i) { return i == 5; }), 10);
|
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()
|
void tst_Algorithm::findOrDefault()
|
||||||
|
|||||||
Reference in New Issue
Block a user