C++中的comparator 发表于 2016-12-18 自定义了对象,如何按照自定对象中某一或多个元素对其进行排序呢?以下分别从C++和Java对其进行实现。一:C++12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455/*实现对自定义的对象类型进行排序(按照其中的元素),首先将对象存放在vector中,然后利用algorithm库函数中的sort对其进行排序,需要重写排序函数以函数名作为函数指针作为sort的第三个参数*/ #include <iostream>#include <string>#include <algorithm>#include <vector>using namespace std; struct students{ int age; string name;}; void addStudents(vector<students> &vec, int age, string name){ students stu; stu.age = age; stu.name = name; vec.push_back(stu); } // 按照年龄进行排序 升序bool sortByAge(const students &s1, const students &s2){ return s1.age < s2.age;} // 先按照年龄进行排序 年纪一样 按照姓名排序bool sortByAll(const students &s1, const students &s2){ if(s1.age < s2.age) return true; else if(s1.age > s2.age) return false; else return s1.name < s2.name;}int main(){ vector<students> vec; addStudents(vec, 20, "zhangming"); addStudents(vec, 20, "xiaoming"); addStudents(vec, 20, "xiaoming2"); addStudents(vec, 23, "xiaohong"); addStudents(vec, 22, "xiaofei"); addStudents(vec, 27, "xiaogang"); cout << "排序前:" << endl; for(vector<students>::iterator iter = vec.begin(); iter != vec.end(); ++iter){ cout << (*iter).age << " " << (*iter).name << endl; } sort(vec.begin(), vec.end(), sortByAll); cout << "排序后:" << endl; for(vector<students>::iterator iter = vec.begin(); iter != vec.end(); ++iter){ cout << (*iter).age << " " << (*iter).name << endl; }}