首先,推荐这篇文章,写的很不错。http://www.cppblog.com/mzty/archive/2005/12/15/1770.html
- 1.sort()函数
//默认
template <class Iterator>
void sort(Iterator first, Iterator last);
//自定义比较函数
template <class Iterator, class Compare>
void sort(Iterator first, Iterator last, Compare Com);
注意:函数参数 first 和 last 都是迭代器,且类似于这样的需要函数列表中含有头迭代器和尾迭代器的函数,一般他们的范围都是【first,last),即这是一个前闭后开区间,
例如:将a[5]={0, 1, 2, 3, 4} 排序,调用sort()函数时,调用方式为sort(a, a+5);
(1) 在默认情况下,sort()函数是按升序排列的,用于比较的方式是使用“<”符号,所以基本类型和string类型都可以使用sort()的默认形式,另外,如果在类中重载“<”符号,同样可以用默认的函数。
例如:
class Test{
pulic:
int data;
bool operator < (const Test &t) const {
return data < t.data;
}
};
int main()
{
Test t[4];
t[0].data = 1;
t[1].data = 5;
t[2].data = 2;
t[3].data = 7;
sort(t, t+4);
for(int i=0; i<4; i++){
cout << t[i].data << " ";
}
cout << endl;
return 0;
}
(2) 在使用自定义的比较函数时,自定义的函数可以是class或struct重载 “()” ,并返回bool的函数。这样的函数成为“仿函数”,另外也可以定义一个函数进行使用。
例如:
#include <iostream>
#include <algorithm>
using namespace std;
class Compare{
public:
bool operator () (int i, int j){
return i < j;
}
}myCom;
//可以使用模板
/*
<pre name="code" class="cpp">class Compare{
public:
template <class T>
bool operator () (T i, T j){
return i < j;
}
}myCom;
*/
int main(){ int a[5] = {1, 4, 5, 7, 3}; sort(a, a+5, myCom); for(int i=0; i<5; i++){ cout << a[i] << " "; } cout << "\n"; return 0;}
另外,可以直接定义函数,注意在定义函数时不能使用模板。
//不能使用模板
bool myFunction(int i, int j){
return i < j;
}
sort(a, a+5, myFunction);
- 2.使用STL中定义的仿函数
equal_to | 相等 |
not_equal_to | 不相等 |
less | 小于 |
greater | 大于 |
less_equal | 小于等于 |
greater_equal | 大于等于 |
- 3 其他排序函数
(1) sort采用成熟的“快速排序算法”(目前大部分STL版本已经不是采用简单的快速排序,而是结合内插排序算法),可以保证很好的平均性能,复杂度为n*log(n)
(2) stable_sort(first, last)
stable_sort(first, last, compare)
功能:对【first,last) 区间的元素进行稳定排序,所谓稳定排序,是指对于原序列中“相等”的元素在完成排列之后的序列中不改变这些“相等”元素的前后位置。
采用“归并排序”,分配足够内存时算法复杂度为n*log(n),否则复杂度为n*log(n)*log(n)。
(3) partial_sort(first, middle, last)
paritial_sort(first, middle, last, compare);
功能:对所有元素进行排序,使【first, middle)排成规定的序列。而【middle, last)的顺序没有规定。
采用“堆排序”(heapsort),它在任何情况下的复杂度为n*log(n),如果希望让partial_sort实现全排序,只要让middle=last。
partial_sort_copy(first, last, result_first, result_last)
partial_sort_copy(first, last, result_first, result_last, compare);
功能:它是copy和partial_sort的组合,首先取出【first, last) 中的元素,然后进行排序,若result_first左溢或result_last-1右溢,则截取【first, last)中【result_first, result_last)的元素,存入【result_first, result_last)中。
若【result_first, result_last) 中含有空余位置,则其他没有填充的位置为原来的元素。
(4) nth_element(first, nth, last)
nth_element(first, nth, last, compare)
功能:它的作用是挑出第nth+1个数据,放在nth迭代器所指的位置,为什么是nth+1个呢?因为数组的开始位置是0,而不是1,所以位置nth,实际上是第nth+1个数据。
实例:
int a[10]={//...};
//假设挑出从小到大排列的第四个数据
nth_element(a, a+3, a+10);
//注意是a+3而不是a+4
- 如果里面有错误内容,还望各位多多指教