forked from qt-creator/qt-creator
Algorithm: Allow sorting container of pointers with member (function)
Change-Id: I2928081750f86b66e969ec2f7ade9e67ce19a825 Reviewed-by: Orgad Shaneh <orgads@gmail.com>
This commit is contained in:
@@ -388,8 +388,10 @@ inline void sort(Container &c, Predicate p)
|
|||||||
template <typename Container, typename R, typename S>
|
template <typename Container, typename R, typename S>
|
||||||
inline void sort(Container &c, R S::*member)
|
inline void sort(Container &c, R S::*member)
|
||||||
{
|
{
|
||||||
std::sort(c.begin(), c.end(), [member](const S &a, const S &b) {
|
auto f = std::mem_fn(member);
|
||||||
return a.*member < b.*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>
|
template <typename Container, typename R, typename S>
|
||||||
inline void sort(Container &c, R (S::*function)() const)
|
inline void sort(Container &c, R (S::*function)() const)
|
||||||
{
|
{
|
||||||
std::sort(c.begin(), c.end(), [function](const S &a, const S &b) {
|
auto f = std::mem_fn(function);
|
||||||
return (a.*function)() < (b.*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});
|
QList<Struct> s4({4, 3, 2, 1});
|
||||||
Utils::sort(s4, &Struct::member);
|
Utils::sort(s4, &Struct::member);
|
||||||
QCOMPARE(s4, QList<Struct>({1, 2, 3, 4}));
|
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)
|
QTEST_MAIN(tst_Algorithm)
|
||||||
|
Reference in New Issue
Block a user