Commit a23e0692 authored by Orgad Shaneh's avatar Orgad Shaneh Committed by Orgad Shaneh
Browse files

Utils: Introduce sort variants for member and member function



Change-Id: Iff29f2c55a08e85de7f0ff4e431f326e351e5305
Reviewed-by: Eike Ziller's avatarEike Ziller <eike.ziller@qt.io>
parent d8e94afb
......@@ -384,6 +384,24 @@ inline void sort(Container &c, Predicate p)
std::sort(c.begin(), c.end(), p);
}
// pointer to member
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;
});
}
// pointer to member function
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)();
});
}
//////////////////
// reverseForeach
/////////////////
......
......@@ -33,6 +33,7 @@ class tst_Algorithm : public QObject
private slots:
void transform();
void sort();
};
......@@ -111,6 +112,32 @@ void tst_Algorithm::transform()
}
}
namespace {
struct Struct
{
Struct(int m) : member(m) {}
bool operator==(const Struct &other) const { return member == other.member; }
int member;
};
}
void tst_Algorithm::sort()
{
QStringList s1({"3", "2", "1"});
Utils::sort(s1);
QCOMPARE(s1, QStringList({"1", "2", "3"}));
QStringList s2({"13", "31", "22"});
Utils::sort(s2, [](const QString &a, const QString &b) { return a[1] < b[1]; });
QCOMPARE(s2, QStringList({"31", "22", "13"}));
QList<QString> s3({"12345", "3333", "22"});
Utils::sort(s3, &QString::size);
QCOMPARE(s3, QList<QString>({"22", "3333", "12345"}));
QList<Struct> s4({4, 3, 2, 1});
Utils::sort(s4, &Struct::member);
QCOMPARE(s4, QList<Struct>({1, 2, 3, 4}));
}
QTEST_MAIN(tst_Algorithm)
#include "tst_algorithm.moc"
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