结构体排序:
写法一
代码语言:javascript复制
QList<test> s;
test aa;
test bb;
test cc;
aa.num = "14";
bb.num = "2";
cc.num = "3";
s.append(aa);
s.append(bb);
s.append(cc);
qSort(s.begin(), s.end(),[](const test &infoA,const test &infoB){return infoA.num.toDouble() < infoB.num.toDouble();});
for(int i = 0; i < s.count() ; i )
{
qDebug() << s.at(i).num;
}
写法二
代码语言:javascript复制#include "widget.h"
#include <QApplication>
#include <QtDebug>
//排列判断
int compare(const test &infoA,const test &infoB)
{
return infoA.num.toDouble() < infoB.num.toDouble();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QList<test> s;
test aa;
test bb;
test cc;
aa.num = "14";
bb.num = "2";
cc.num = "3";
s.append(aa);
s.append(bb);
s.append(cc);
qSort(s.begin(), s.end(),compare);
for(int i = 0; i < s.count() ; i )
{
qDebug() << s.at(i).num;
}
return a.exec();
}
Qt中可以使用qSort可以对容器排序,助手中有很多示例,大多数关于int、QString的排序,今天这里主要讲解qSort如何对结构体进行排序的。
Qt对整形排序:
代码语言:javascript复制QList list;
list << 33 << 12 << 68 << 6 << 12;
qSort(list.begin(), list.end());
// list: [ 6, 12, 12, 33, 68 ]
Qt对字符串排序:
代码语言:javascript复制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" ]
}
Qt对结构体排序:
代码语言:javascript复制struct BarAmount
{
int barLevel; //钢筋级别
QString diameter; //钢筋直径
double planAmount; //计划量
double purchaseAmount; //采购量
double amount; //总量
};
结构体如上所示, 对QList barDataList可通过以下方式进行排序!
代码语言:javascript复制void OverdraftControl::sortBarData(QList *barDataList)
{
qSort(barDataList->begin(), barDataList->end(), compareBarData);
}
代码语言:javascript复制bool compareBarData(const BarAmount &barAmount1, const BarAmount &barAmount2)
{
if (barAmount1.barLevel < barAmount2.barLevel)
{
return true;
}
else if (barAmount1.barLevel > barAmount2.barLevel)
{
return false;
}
else
{
QString strDiameter1 = barAmount1.diameter;
QString strDiameter2 = barAmount2.diameter;
int nCompare = compareDiameterDescription(strDiameter1,strDiameter2);
if (nCompare == -1)
{
return true;
}
else if (nCompare == 1)
{
return false;
}
else
{
return true;
}
}
}
直接调用sortBarData(&barDataList)就可以完成对QList barDataList的排序了!