#include <vector> #include <algorithm> 一、vector保存的是基础数据类型(int、char、float等) vector<int> vInt; vInt.push_back(1); vInt.push_back(3); vInt.push_back(2); vInt.push_back(100); vInt.push_back(15); sort(vInt.begin(), vInt.end()); // 从小到大 二、vector保存的是自定义数据类型 struct Person { string Name; string Sex; int Age; int High; Person() :Age(0) ,High(0) { } }; 方法一: //定义比较函数 bool CmpAge(const Person& p1,const Person& p2) { return p1.Age < p2.Age;//小于号表示:从小到大排序(小的在前,大的在后) //大于号相反 } 方法二: 结构体重载比较函数: struct Person { string Name; string Sex; int Age; int High; Person() :Age(0) ,High(0) { } bool operator < (const Person& obj) const //重载小于操作符,函数最后的 const 别忘了,否则会报错。(详见:http://www.cnblogs.com/SZxiaochun/p/7731900.html) { return Age < obj.Age; } }; //定义比较函数 bool CmpAge(Person& p1,Person& p2) (参数不要 const,否则报错) { return p1 < p2;//小于号表示:从小到大排序(小的在前,大的在后) //大于号相反 } Person per1,per2; per1.Name = "xiaochun"; per1.Sex = "男"; per1.Age = 21; per1.High = 168; per2.Name = "chunxiao"; per2.Sex = "男"; per2.Age = 22; per2.High = 168; vector<Person> vec_Person; vec_Person.pushback(per1); vec_Person.pushback(per2); //排序 sort(vec_Person.begin(),vec_Person.end(),CmpAge); //vector输出 //省略 ......