C++list中使用sort排序

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//定义学生类
class Student
{
public:
string StuName; //姓名
string StuNum; //学号
string Sex; //性别
//成绩
float English; //英语
float SQL; //SQL
float Prob; //概率论
float Circuit; //电路
float CSharp; //C#
float Average; //平均成绩
};
list studList;

已经用list存入数据了,如何将list里的数据按平均成绩排序

如果你在使用c++ 11,你可以用lambda表达式
//用平均成绩排序
list.sort( -> bool
{
return a.Average > b.Average;
});
//用c#成绩排序
list.sort( -> bool
{
return a.Average > b.Average;
});

如果是c++11以下版本,你可以有用
1. 函数
bool compare_avaerage (const Student& first, const Student& second)
{
return a.Average > b.Average;
}
然后调用list.sort(compare_average);
2. Function class
class StudentSorter{
public:
operator() (const Student& s1, const Student& s2)
{
// get the field to sort by and make the comparison
return a.Average > b.Average;
}
}
然后你可以调用
StudentSorter sorter;
sort(list.begin(), list.end(), sorter);

http://en.cppreference.com/w/cpp/container/list/sort

使用list的sort函数即可,只需要提供一个比较函数

#include
#include
#include
#include
#include

using namespace std;
// 定义学生类
class Student
{
public:
string StuName; // 姓名
string StuNum; // 学号
string Sex; // 性别
// 成绩
float English; // 英语
float SQL; // SQL
float Prob; // 概率论
float Circuit; // 电路
float CSharp; // C#
float Average; // 平均成绩
public:
};

// Q:
// 已经用list存入数据了,如何将list里的数据按平均成绩排序
// A:
// 使用list的sort方法, 自己提供一比较函数即可

bool CmpAvg(const Student& lhs, const Student& rhs)
{
return lhs.Average < rhs.Average;
}

int
main(int argc, char *argv[])
{
Student foo;
list bar;
list::const_iterator it;

foo.StuNum = "1";
foo.Average = 75;
bar.push_back(foo);

foo.StuNum = "2";
foo.Average = 95;
bar.push_back(foo);

foo.StuNum = "3";
foo.Average = 85;
bar.push_back(foo);

for (it = bar.begin(); it != bar.end(); ++it) {
    cout << it->StuNum << "," << it->Average << endl;
}
cout << endl;

bar.sort(CmpAvg);
for (it = bar.begin(); it != bar.end(); ++it) {
    cout << it->StuNum << "," << it->Average << endl;
}
cout << endl;

return 0;

}