Qt之qSort

 
Qt中可以使用qSort可以对容器排序,助手中有很多示例,大多数关于int、QString的排序,今天这里主要讲解qSort如何对结构体进行排序的。

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可通过以下方式进行排序!
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)就可以完成对QListbarDataList的排序了!

你可能感兴趣的:(Qt之qSort)