結構體排序:
寫(xiě)法一
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; }寫(xiě)法二
#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可以對容器排序,助手中有很多示例,大多數關(guān)于int、QString的排序,今天這里主要講解qSort如何對結構體進(jìn)行排序的。
Qt對整形排序:
QList list;
list << 33 << 12 << 68 << 6 << 12;
qSort(list.begin(), list.end());
// list: [ 6, 12, 12, 33, 68 ]Qt對字符串排序:
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對結構體排序:
struct BarAmount
{
int barLevel; //鋼筋級別
QString diameter; //鋼筋直徑
double planAmount; //計劃量
double purchaseAmount; //采購量
double amount; //總量
};結構體如上所示, 對QList barDataList可通過(guò)以下方式進(jìn)行排序!
void OverdraftControl::sortBarData(QList *barDataList)
{
qSort(barDataList->begin(), barDataList->end(), compareBarData);
}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的排序了!
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。