上一篇我们讲到STL map的key如果由多个值组成,并按照这些值分别进行排序的情况。在最后的结论中我们说到“通常我们不用STL algorithm中的sort函数,来对一个map进行排序,而对vector的元素进行排序则可以很方面地使用sort函数。”
下面就是一个完整的,vector按多字段值进行排序的示例代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Student
{
private:
int id; // 学号
string name; // 姓名
float eyesight; // 视力
float height; // 身高
float chinese; // 语文成绩
float english; // 英文成绩
float math; // 数学成绩
public:
Student(int id, string name, float eyesight, float height, float chinese, float english, float math)
{
this->id = id;
this->name = name;
this->eyesight = eyesight;
this->height = height;
this->chinese = chinese;
this->english = english;
this->math = math;
}
int get_id()
{
return id;
}
string get_name()
{
return name;
}
float get_eyesight()
{
return eyesight;
}
float get_height()
{
return height;
}
float get_chinese()
{
return chinese;
}
float get_english()
{
return english;
}
float get_math()
{
return math;
}
};
// 比较大小的函数(谓词)
bool comparer(Student& stu_a, Student& stu_b)
{
// 按eyesight升序 + height升序排列
if(stu_a.get_eyesight() != stu_b.get_eyesight())
return (stu_a.get_eyesight() < stu_b.get_eyesight());
else
return (stu_a.get_height() < stu_b.get_height());
// 按eyesight降序° + height降序排列
//if(stu_a.get_eyesight() != stu_b.get_eyesight())
// return (stu_a.get_eyesight() > stu_b.get_eyesight());
//else
// return (stu_a.get_height() > stu_b.get_height());
// 按eyesight升序 + height降序排列
//if(stu_a.get_eyesight() != stu_b.get_eyesight())
// return (stu_a.get_eyesight() < stu_b.get_eyesight());
//else
// return (stu_a.get_height() > stu_b.get_height());
// 按eyesight降序 + height升序排列
//if(stu_a.get_eyesight() != stu_b.get_eyesight())
// return (stu_a.get_eyesight() > stu_b.get_eyesight());
//else
// return (stu_a.get_height() < stu_b.get_height());
}
int main(int argc, char** argv)
{
vector<Student> vec;
vec.push_back(Student(4, "Dudley", 1.1f, 170.2f, 90.5f, 89.5f, 93.0));
vec.push_back(Student(3, "Chris", 1.1f, 163.4f, 93.5f, 90.0f, 83.5f));
vec.push_back(Student(2, "Bob", 1.5f, 166.6f, 86.0f, 98.5f, 85.0f));
vec.push_back(Student(1, "Andrew", 1.5f, 173.2f, 98.5f, 100.0f, 100.f));
// 调用STL中的sort函数,其中的第三个参数就是我们前面定义的,比较两个Student对象大小的函数
sort(vec.begin(), vec.end(), comparer);
vector<Student>::iterator iter;
for(iter = vec.begin(); iter != vec.end(); ++iter)
{
cout << (*iter).get_eyesight() << "\t" << (*iter).get_height() << endl;
}
return 0;
}
输出的结果为:
1.1 163.4
1.1 170.2
1.5 166.6
1.5 173.2