Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

sorting

qt

class MyClass {
  public:
    int a;
    bool operator<(const MyClass other) const {
        return a<other.a;
    }
    ....
};
....
QList<MyClass*> list;
like image 405
kuzmich Avatar asked Feb 24 '11 10:02

kuzmich


3 Answers

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(); });
like image 147
Silicomancer Avatar answered Oct 26 '22 23:10

Silicomancer


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>());
like image 40
decltype Avatar answered Oct 27 '22 00:10

decltype


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

like image 32
Šimon Tóth Avatar answered Oct 27 '22 00:10

Šimon Tóth