Commit c3ee2d06 authored by Eike Ziller's avatar Eike Ziller
Browse files

Algorithm: Allow sorting container of pointers with member (function)



Change-Id: I2928081750f86b66e969ec2f7ade9e67ce19a825
Reviewed-by: Orgad Shaneh's avatarOrgad Shaneh <orgads@gmail.com>
parent a23e0692
......@@ -388,8 +388,10 @@ inline void sort(Container &c, Predicate p)
template <typename Container, typename R, typename S>
inline void sort(Container &c, R S::*member)
{
std::sort(c.begin(), c.end(), [member](const S &a, const S &b) {
return a.*member < b.*member;
auto f = std::mem_fn(member);
using const_ref = typename Container::const_reference;
std::sort(c.begin(), c.end(), [&f](const_ref a, const_ref b) {
return f(a) < f(b);
});
}
......@@ -397,8 +399,10 @@ inline void sort(Container &c, R S::*member)
template <typename Container, typename R, typename S>
inline void sort(Container &c, R (S::*function)() const)
{
std::sort(c.begin(), c.end(), [function](const S &a, const S &b) {
return (a.*function)() < (b.*function)();
auto f = std::mem_fn(function);
using const_ref = typename Container::const_reference;
std::sort(c.begin(), c.end(), [&f](const_ref a, const_ref b) {
return f(a) < f(b);
});
}
......
......@@ -136,6 +136,16 @@ void tst_Algorithm::sort()
QList<Struct> s4({4, 3, 2, 1});
Utils::sort(s4, &Struct::member);
QCOMPARE(s4, QList<Struct>({1, 2, 3, 4}));
// member function with pointers
QList<QString> arr1({"12345", "3333", "22"});
QList<QString *> s5({&arr1[0], &arr1[1], &arr1[2]});
Utils::sort(s5, &QString::size);
QCOMPARE(s5, QList<QString *>({&arr1[2], &arr1[1], &arr1[0]}));
// member with pointers
QList<Struct> arr2({4, 1, 3});
QList<Struct *> s6({&arr2[0], &arr2[1], &arr2[2]});
Utils::sort(s6, &Struct::member);
QCOMPARE(s6, QList<Struct *>({&arr2[1], &arr2[2], &arr2[0]}));
}
QTEST_MAIN(tst_Algorithm)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment