#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輸出
//省略
......