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 <eike.ziller@theqtcompany.com>
This commit is contained in:
Tobias Hunger
2015-10-27 11:01:34 +01:00
parent 5babad8c38
commit 7d4078b963

View File

@@ -35,6 +35,8 @@
#include <algorithm>
#include <functional>
#include <tuple>
#include <QStringList>
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<typename C, typename F>
Q_REQUIRED_RESULT
std::tuple<C, C> 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<typename C, typename R, typename S>
Q_REQUIRED_RESULT
std::tuple<C, C> partition(const C &container, R (S::*predicate)() const)
{
return partition(container, std::mem_fn(predicate));
}
//////////////////
// sort
/////////////////