class MyClass {
public:
int a;
bool operator<(const MyClass other) const {
return a<other.a;
}
....
};
....
QList<MyClass*> list;
In C++11 you can also use a lambda like this:
QList<const Item*> l;
qSort(l.begin(), l.end(),
[](const Item* a, const Item* b) -> bool { return a->Name() < b->Name(); });
A general solution to the problem would be to make a generic less-than function object that simply forwards to the pointed-to-type's less-than operator. Something like:
template <typename T>
struct PtrLess // public std::binary_function<bool, const T*, const T*>
{
bool operator()(const T* a, const T* b) const
{
// may want to check that the pointers aren't zero...
return *a < *b;
}
};
You could then do:
qSort(list.begin(), list.end(), PtrLess<MyClass>());
Make your own comparator, that will work with pointers and then use qSort: http://qt-project.org/doc/qt-5.1/qtcore/qtalgorithms.html#qSort-3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With