Qt中自带的qSort排序功能,可以对各种内置类型进行排序,比如int, double, string等,使用也非常简单,直接qSort(list.begin(), list.end());就可以了而如果要对结构体对象进行排序呢,这个时候就需要自己定义一个比如函数,然后qsort调用,下面看具体的代码实现。
void MainWindow::slotIntSort()
{
QList<int> intList = {45, 36, 89, 32, 68, 75, 54, 18};
qDebug() << "int sort before========" << intList;
qSort(intList.begin(), intList.end());
qDebug() << "int sort after=========" << intList;
}
void MainWindow::slotDoubleSort()
{
QVector<double> doubleVec = {45.5, 36.4, 89.3, 32.7, 68.2, 75.8, 54.6, 18.1};
qDebug() << "double sort before=====" << doubleVec;
qSort(doubleVec.begin(), doubleVec.end());
qDebug() << "double sort after======" << doubleVec;
}
void MainWindow::slotStringSort()
{
QStringList strList = {"Chris", "Burt", "Colin", "Alexis", "John", "Tom", "Ronald", "Malcolm"};
qDebug() << "string sort before=====" << strList;
qSort(strList.begin(), strList.end());
qDebug() << "string sort after======" << strList;
}
struct userInfo
{
QString name; //名字
double weight; //体重
int age; //年龄
int height; //身高
};
bool fieldCompare(const userInfo &info1, const userInfo &info2)
{
//升序
//return info1.age < info2.age;//按age升序排序
//return info1.height < info2.height;//按height升序排序
return info1.weight < info2.weight;//按weight升序排序
//return info1.name < info2.name;//按name升序排序
//降序
//return info1.age < info2.age;
//return info1.height < info2.height;
//return info1.weight < info2.weight;
//return info1.name < info2.name;
}
void MainWindow::slotStructSort()
{
QList<userInfo> list;
userInfo info1;
info1.name = "Chris";
info1.age = 20;
info1.height = 175;
info1.weight = 62.5;
list.append(info1);
userInfo info2;
info2.name = "Burt";
info2.age = 18;
info2.height = 169;
info2.weight = 63.5;
list.append(info2);
userInfo info3;
info3.name = "Alexis";
info3.age = 27;
info3.height = 185;
info3.weight = 61.5;
list.append(info3);
userInfo info4;
info4.name = "Tom";
info4.age = 29;
info4.height = 165;
info4.weight = 67.5;
list.append(info4);
userInfo info5;
info5.name = "Malcolm";
info5.age = 30;
info5.height = 172;
info5.weight = 66.5;
list.append(info5);
qDebug() << "struct sort before=====";
for(int i = 0; i < list.size(); ++i)
{
qDebug() << "list[" << i << "].weight=" << list[i].weight
<< "list[" << i << "].age=" << list[i].age
<< "list[" << i << "].height=" << list[i].height
<< "list[" << i << "].name=" << list[i].name;
}
qSort(list.begin(), list.end(), fieldCompare);
qDebug() << "struct sort after======";
for(int i = 0; i < list.size(); ++i)
{
qDebug() << "list[" << i << "].weight=" << list[i].weight
<< "list[" << i << "].age=" << list[i].age
<< "list[" << i << "].height=" << list[i].height
<< "list[" << i << "].name=" << list[i].name;
}
}
运行结果: