全部范围的排序: | 功能简要描述 |
sort(beg,end) | 实现元素的排序(快速排序),默认递增 |
sort(beg,end,cmp) | 自定义排序规则 |
stable_sort(beg, end) stable_sort(beg, end,cmp) |
排序算法是稳定的 |
部分范围的排序 | 功能简要描述 |
partial_sort(beg, mid, end) | 局部范围的排序,middle之前的元素是已排序的 |
partial_sort(beg, mid, end, comp) | 自定义排序规则 |
partial_sort_copy(beg, mid, end) | |
partial_sort_copy(beg, mid, end, comp) | |
划分 | 功能简要描述 |
nth_element(beg, nth, end) | 容器中的元素围绕 nth 划分:nth 之前的元素都小于或等于 nth 所表示的值,nth 之后的元素都大于或等于它。 |
nth_element(beg, nth, end, comp) | 该算法可实现自定义的排序规则 |
partition(beg, end, unaryPred) | 将元素划分为两组,有第三个参数决定划分规则,第三个参数返回真,则将元素放在前面;否则,放在后面。算法不稳定。 |
stable_partition(beg, end, unaryPred) | 该算法为稳定划分 |
注:
1、beg,end,mid,nth为迭代器或者要求序列的起点,终点
2、comp为二元函数,返回值为bool;
常见有三种表达方式:
1)函数:
bool myCmp(T a, T b){
……
return ……;
}
如:
bool myCmp( int a,int b){
return a<b;
}
推荐写法(这样 a,b不会被修改,提高安全性)
bool myCmp(const int& a,const int& b){
return a<b;
}
2)对象
struct 名字{
bool operator()(T a,T b){…… return …… ;}
}对象名;
如:
struct obj{
bool operator() (int a,int b){
return a<b;
}
}myobject;
3)使用头文件#include<functional>中的函数对象(最推荐)
源码可查询官网文档:http://www.cplusplus.com/reference/
如:less<Type>()
函数对象类模板 | 成员函数 T operator ( const T & x, const T & y) 的功能(返回值为bool) |
---|---|
plus <Type> | return x + y; |
minus <Type > | return x - y; |
multiplies <Type> | return x * y; |
divides <Type> | return x / y; |
modulus <Type> | return x % y; |
成员函数 bool operator( const T & x, const T & y) 的功能 | |
equal_to <Type> | return x == y; |
not_equal_to <Type> | return x! = y; |
greater <Type> | return x > y; |
less <Type> | return x < y; |
greater_equal <Type> | return x > = y; |
less_equal <Type> | return x <= y; |
logical_and <Type> | return x && y; |
logical_or <Type> | return x || y; |
成员函数 T operator( const T & x) 的功能 | |
negate <Type> | return - x; |
成员函数 bool operator( const T & x) 的功能 | |
logical_not <Type> | return ! x; |
3、unaryPred为一元函数,返回bool
如
bool 函数名 (T a){
……
return ……;
}