From 7d4078b9635b2c4babcb2c3e7ef77d6d7b23c91b Mon Sep 17 00:00:00 2001 From: Tobias Hunger Date: Tue, 27 Oct 2015 11:01:34 +0100 Subject: [PATCH] Algorithm: Add partition functions These take a container and a predicate and return a Partition struct with the hit and miss fields. Any element in the original container will end up in either hit or miss, depending on whether the predicate returned true for the element or not. Change-Id: Ia02cd704d6fe1388dc677308440acc48f7c9c1e1 Reviewed-by: Eike Ziller --- src/libs/utils/algorithm.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/libs/utils/algorithm.h b/src/libs/utils/algorithm.h index fa3ebabe5d..ba3b4f4aad 100644 --- a/src/libs/utils/algorithm.h +++ b/src/libs/utils/algorithm.h @@ -35,6 +35,8 @@ #include #include +#include + #include namespace Utils @@ -359,6 +361,39 @@ C filtered(const C &container, R (S::*predicate)() const) return out; } +////////////////// +// partition +///////////////// + +// Recommended usage: +// C hit; +// C miss; +// std::tie(hit, miss) = Utils::partition(container, predicate); + +template +Q_REQUIRED_RESULT +std::tuple partition(const C &container, F predicate) +{ + C hit; + C miss; + auto hitIns = inserter(hit); + auto missIns = inserter(miss); + foreach (auto i, container) { + if (predicate(i)) + hitIns = i; + else + missIns = i; + } + return std::make_tuple(hit, miss); +} + +template +Q_REQUIRED_RESULT +std::tuple partition(const C &container, R (S::*predicate)() const) +{ + return partition(container, std::mem_fn(predicate)); +} + ////////////////// // sort ///////////////// -- GitLab