STL vector按多字段值排序

来源:互联网 发布:js原型和原型链 面试题 编辑:程序博客网 时间:2024/06/05 18:22

转自:http://blog.csdn.net/pathuang68/article/details/7526381

上一篇我们讲到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)在gcc下error : invalid initialization of reference of type ‘Student&’ from expression of type ‘const Student’ 常引用const无法初始化 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());elsereturn (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;Student student(4, "Dudley", 1.1f, 170.2f, 90.5f, 89.5f, 93.0);vec.push_back(student);Student student2(3, "Chris", 1.1f, 163.4f, 93.5f, 90.0f, 83.5f);vec.push_back(student2);Student student3(2, "Bob", 1.5f, 166.6f, 86.0f, 98.5f, 85.0f);vec.push_back(student3);Student student4(1, "Andrew", 1.5f, 173.2f, 98.5f, 100.0f, 100.f);vec.push_back(student4);// 调用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()<<"\t"<<(*iter).get_name() << endl;}return 0;}


0 0
原创粉丝点击