kuzmich
kuzmich

Reputation: 163

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;
    }
    ....
};
....
QList<MyClass*> list;

Upvotes: 16

Views: 32764

Answers (3)

Silicomancer
Silicomancer

Reputation: 9166

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(); });

Upvotes: 15

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36433

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

Upvotes: 9

decltype
decltype

Reputation: 1601

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>());

Upvotes: 13

Related Questions