C++ STL, sort用法。

 

在algorithm头文件中的sort可以给任意对象排序,包括内置类型和自定义类型,前提是定义了“<“运算符。

sort(begin,end),表示一个范围,例如:


 1 #include"iostream"
 2 #include"algorithm" 
 3 using namespace std; 
 4 bool compare(int a,int b){
 5     return a>b;
 6 }
 7 
 8 int main(){
 9     int a[5]={9,2,4,6,8};
10     sort(a,a+5);
11     for(int i=0;i<5;i++){
12         cout<<a[i];
13     }
14     cout<<endl;
15     
16     
17     sort(a,a+5,compare);
18     for(int i=0;i<5;i++){
19         cout<<a[i];
20     }
21     return 0;
22 }

 


 上述排序代码省略了一个compare函数,sort使用数组元素默认的大小比较运算符进行排序,只有在需要按照特殊依据进行排序是才需要传入额外的比较函数。

 

posted @ 2016-03-24 22:53  Hutonm  阅读(314)  评论(0编辑  收藏  举报