class MyClass {
public:
int a;
bool operator<(const MyClass other) const {
return a<other.a;
}
....
};
....
QList<MyClass*> list;
答案 0 :(得分:13)
该问题的一般解决方案是创建一个通用的小于函数的对象,它只是转发给指向类型的less-than运算符。类似的东西:
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;
}
};
然后你可以这样做:
qSort(list.begin(), list.end(), PtrLess<MyClass>());
答案 1 :(得分:10)
在C ++ 11中,你也可以使用这样的lambda:
QList<const Item*> l;
qSort(l.begin(), l.end(),
[](const Item* a, const Item* b) -> bool { return a->Name() < b->Name(); });
答案 2 :(得分:9)
创建自己的比较器,使用指针,然后使用qSort:http://qt-project.org/doc/qt-5.1/qtcore/qtalgorithms.html#qSort-3