您的位置:首页 > 编程语言 > C语言/C++

c++11版本list中sort用lambda表达式

2015-07-09 15:47 459 查看
//定义学生类

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;

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: