class MyClass {
public:
int a;
bool operator<(const MyClass other) const {
return a<other.a;
}
....
};
....
QList<MyClass*> list;
Run Code Online (Sandbox Code Playgroud)
dec*_*ype 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;
}
};
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
qSort(list.begin(), list.end(), PtrLess<MyClass>());
Run Code Online (Sandbox Code Playgroud)
Sil*_*cer 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(); });
Run Code Online (Sandbox Code Playgroud)
制作自己的比较器,使用指针,然后使用qSort:http://qt-project.org/doc/qt-5.1/qtcore/qtalgorithms.html#qSort-3