C++ 如何使用 Qt 库(可能是 qSort())对 QList<MyClass*> 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5103682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:24:35  来源:igfitidea点击:

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

c++qtsorting

提问by kuzmich

class MyClass {
  public:
    int a;
    bool operator<(const MyClass other) const {
        return a<other.a;
    }
    ....
};
....
QList<MyClass*> list;

采纳答案by ?imon Tóth

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

制作您自己的比较器,它将与指针一起使用,然后使用 qSort:http: //qt-project.org/doc/qt-5.1/qtcore/qtalgorithms.html#qSort-3

回答by decltype

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

回答by Silicomancer

In C++11 you can also use a lambda like this:

在 C++11 中,您还可以使用这样的 lambda:

QList<const Item*> l;
qSort(l.begin(), l.end(), 
      [](const Item* a, const Item* b) -> bool { return a->Name() < b->Name(); });