STL提供了好几种算法对区间内的元素排序。出来完全排序外,还支持局部排序。

 

对所有元素排序

void 

sort(RandomAccessIterator beg,RandomAccessIterator end)

void 

sort(RandomAccessIterator beg,RandomAccessIteratro end,

       BinaryPredicate op)

 

void

stable_sort(RandomAccessIterator beg,RandomAccessIterator end)

void 

stable_sort(RandomAccessIterator beg,RandomAccessIterator end,

                   BinaryPredicate op)

1.sort()和stable_sort()的上述第一形式,使用operator<对区间[beg,end)内的所有元素进行排序

2.sort()和stable_sort()的上述第二形式,使用判断式op(elem1,elem2)作为排序准则,对区间[beg,end)内的所有元素进行排序

3.sort()和stable_sort()的区别是,后者保证相等元素的原本相对次序在排序后保持不变。

 

下面这个例子示范sort()的用法

 1 #include "algostuff.hpp"
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     deque<int> coll;
 7     INSERT_ELEMENTS(coll,1,9);
 8     INSERT_ELEMENTS(coll,1,9);
 9     PRINT_ELEMENTS(coll,"on entry: ");
10     sort(coll.begin(),coll.end());
11     PRINT_ELEMENTS(coll,"sorted: ");
12     sort(coll.begin(),coll.end(),greater<int>());
13     PRINT_ELEMENTS(coll,"sorted >:"); 
14 }
View Code

相关文章: