STL 容器的排序


1.sort函数,头文件#include<Algorithm>

  1. template <class RandomAccessIterator>  
  2.   void sort ( RandomAccessIterator first, RandomAccessIterator last );  
  3.   
  4. template <class RandomAccessIterator, class Compare>  
  5.   void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );  
优势:对于线型容器可以直接使用,方便。如vector、list。并且可以自定义比较规则。
缺点:容器中的对象需要是可以对比的。或自定义规则。对于非线性容器无法排序如map.

2.Map容器:map容器本身自带key排序。但是要求key是可以对比的。
template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map;
template <class T> struct less : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const
    {return x<y;}
};
template <class T> struct greater : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const
    {return x>y;}
};
  map<string, int, greater<string> > name_score_map;
若需要按照value排序:可以采用以下方式:
typedef pair<string, int> PAIR;  
int cmp(const PAIR& x, const PAIR& y) 
{   return x.second > y.second;  } 
map<string,int> m;  
vector<PAIR> vec(m.beging(),m.end());  
sort(vec.begin(), vec.end(), cmp); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值