c sort函式總結

2021-08-31 18:10:26 字數 1042 閱讀 4821

sort函式經常在演算法題中被使用,這裡對其用法進行總結:

一、需要使用標頭檔案#include和using namespace std;  

二、語法:sort(begin,end,cmp),cmp引數可以省略,預設按公升序排序。

1)begin是要排序的陣列的起始位址。

2)end是最後一位要排序的位址。 3)第三個引數是排序的方式,可以是從大到小也可是從小到大,省略時預設的排序方法是從小到大排序。

三、使用時:

1、陣列的使用:

#include#include#includeusing namespace std;

int cmp(int a,int b)

int main()

; sort(a,a+5);//預設公升序排序,輸出1,2,5,7,10

for(int i=0;i<5;i++)

cout<2、string型別的使用:

#include#include#includeusing namespace std;

int main()

int main () ;

vectorv (a, a+5);

sort (v.begin(),v.begin()+3); //(1,2,7),5,10

sort (v.begin(),v.end(),cmp); //10,7,5,2,1

cout << "vector sort:";

for (vector::iterator it=v.begin(); it!=v.end(); ++it)

cout << ' ' << *it;

cout << '\n';

return 0;

}

4、結構體的使用:

#include#include#includeusing namespace std;

struct s;

bool cmp(s x,s y)

int main()

C sort函式使用總結

標頭檔案 algorithm 對於 整數 字元 陣列進行比較時,可直接通過sort a,a n 或sort a.begin a.end 進行排序,預設公升序排列,須要高速實現降序時,有三種方案 1.反轉公升序陣列 reserve函式 2.反向迭代sort a.rend a.rbegin 3.借助c ...

C sort排序函式的用法總結

標準模板庫stl中的sort 函式,時間複雜度為n log2 n 執行效率較高。sort 函式可以三個引數也可以兩個引數 必須的標頭檔案 include algorithm 和using namespace std。它使用的排序方法類似於快排,時間複雜度為n log2 n sort 函式有三個引數 ...

C sort 函式用法

msdn中的定義 template voidsort ranit first,ranit last 1 template voidsort ranit first,ranit last,pred pr 2 標頭檔案 include using namespace std 1.預設的sort函式是按公...