开发者

How to sort QList<MyClass*> using Qt library (maybe qSort())?

class MyClass {
  public:
    int a;
    bool operator<(const MyClass other) const {
        return a<other.a;
    }
    ....
开发者_StackOverflow中文版};
....
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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜