我有一个自定义类型 Class1,其中 bool operator < (Class1& other);
已定义。
我还有一些容器,例如 QVector<Class1*> container;
当我使用 qSort(container.begin(),container.end());
时项目按其内存地址排序。
然后我决定实现bool operator < (Class1* other);
但排序以相同的方式执行。
最佳答案
您需要为 qSort
function 提供一个 LessThan
函数.这是文档中的示例:
void qSort ( RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan )
This is an overloaded function.
Uses the lessThan function instead of operator<() to compare the items.
For example, here's how to sort the strings in a QStringList in case-insensitive alphabetical order:
bool caseInsensitiveLessThan(const QString &s1, const QString &s2)
{
return s1.toLower() < s2.toLower();
}
int doSomething()
{
QStringList list;
list << "AlPha" << "beTA" << "gamma" << "DELTA";
qSort(list.begin(), list.end(), caseInsensitiveLessThan);
// list: [ "AlPha", "beTA", "DELTA", "gamma" ]
}
关于c++ - 类型*元素容器的qt排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16737173/