C++学习记录之STL函数

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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值