1、排序函数
sort (): 对给定区间所有元素进行排序
stable_sort: 对给定区间所有元素进行稳定排序
partial_sort: 对给定区间所有元素部分排序
partial_sort_copy: 对给定区间复制并排序 nth_element 找出给定区间的某个位置对应的元素 is_sorted 判断一个区间是否已经排好序 partition,使得符合某个条件的元素放在前面
stable_partition: 相对稳定的使得符合某个条件的元素放在前面
使用排序函数要加入#include <algorithm>头文件
(1)对基本类型数据从小到大排序
sort(vec.begin(),vec.end(),less<int>());
(2)对基本类型数据从大到小排序
sort(vec.begin(),vec.end(),greater<int>());
(3)对自定义结构体从小到大排序或者从大到小排序,自定义结构体必须重载operator <函数来指定按照什么规则来排序
struct tGame//自定义排序结构体
{
int iNum;
char name[20];
tGame()
{
memset(this,0,sizeof(tGame));
}
bool operator <(const tGame &t) const//重载operator<函数指定按照iNum从小到大排序
{
return iNum<t.iNum;
}
}
std::vector<tGame> vec;
vec.clear();
tGame RedGames[5];
RedGames[0].iNum=10;
memcpy(RedGames[0].name,"RedCf ",sizeof(RedGames[0].name));
RedGames[1].iNum=20;
memcpy(RedGames[1].name,"NiZhan ",sizeof(RedGames[1].name));
RedGames[2].iNum=20;
memcpy(RedGames[2].name,"XuanWu ",sizeof(RedGames[2].name));
RedGames[3].iNum=50;
memcpy(RedGames[3].name,"YingXiong ",sizeof(RedGames[3].name));
RedGames[4].iNum=200;
memcpy(RedGames[4].name,"KeKeKeLe ",sizeof(RedGames[4].name));
for(int i=0;i<5;i++)
{
vec.push_back(RedGames[i]);
}
sort(vec.begin(),vec.end());
(4)对类排序
class Game
{
public:
int iNum;
char name[20];
Game()
{
iNum=0;
memset(name,0,sizeof(name));
}
bool operator <(const Game &t) const
{
return iNum>t.iNum;
}
};
std::vector<Game> vec;
vec.clear();
Game RedGames[5];
RedGames[0].iNum=10;
memcpy(RedGames[0].name,"RedCf ",sizeof(RedGames[0].name));
RedGames[1].iNum=20;
memcpy(RedGames[1].name,"NiZhan ",sizeof(RedGames[1].name));
RedGames[2].iNum=20;
memcpy(RedGames[2].name,"XuanWu ",sizeof(RedGames[2].name));
RedGames[3].iNum=50;
memcpy(RedGames[3].name,"YingXiong ",sizeof(RedGames[3].name));
RedGames[4].iNum=200;
memcpy(RedGames[4].name,"KeKeKeLe ",sizeof(RedGames[4].name));
for(int i=0;i<5;i++)
{
vec.push_back(RedGames[i]);
}
sort(vec.begin(),vec.end());