1.sort函数,头文件#include<Algorithm>
- template <class RandomAccessIterator>
- void sort ( RandomAccessIterator first, RandomAccessIterator last );
- template <class RandomAccessIterator, class Compare>
- 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);