c – 如何在QList中使用qSort和自定义类型?
作者:互联网
我在排序包含结构实例的QList时遇到问题:
class modelHeuristic
{
typedef struct {
QString c;
QString t;
double value;
}Saving;
public:
QList<Saving> list_saving;
#include "klarkeright.h"
klarkeRight::klarkeRight()
{
}
void klarkeRight::Algoritmo_Asimetrico(modelHeuristic *model)
{
qSort(model->list_saving.begin(), model->list_saving.end());
}
error: invalid operands to binary expression (‘const modelHeuristic::Saving’ and ‘const modelHeuristic::Saving’)
return (t1 < t2);
解决方法:
首先,QtAlgorithms主要被弃用,你不应该使用它.请按照Qt文档的建议使用std::sort.
否则,您将需要实现实际的比较功能,因为您似乎正在使用自定义类型.当然,通用算法无法知道如何与这样的自定义项进行比较.这就是错误试图指出的.
然后,您需要将该函数作为第三个参数传递给排序算法,或者将其命名为operator<.我更喜欢明确,特别是从那以后你可以将你的比较限制在它所依赖的类中. 因此,我会写这样的东西: main.cpp中
#include <QtAlgorithms>
#include <QString>
#include <QList>
class modelHeuristic
{
typedef struct {
QString c;
QString t;
double value;
} Saving;
public:
static bool savingComparison(const Saving &s1, const Saving &s2)
{
return s1.value < s2.value; // This is just an example
}
QList<Saving> list_saving;
};
int main()
{
modelHeuristic *model = new modelHeuristic();
// This is not doing anything useful with an empty list
// that is constructed, but it shows how to get the theory right!
// Also, you really wish to use std::sort here instead.
qSort(model->list_saving.begin(), model->list_saving.end(), modelHeuristic::savingComparison);
return 0;
}
main.pro
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
构建并运行
qmake && make && ./main
有关详细信息,请参阅documentation.
标签:qtcore,qlist,c,sorting,qt 来源: https://codeday.me/bug/20190722/1505931.html