用法
1、sort函數可以三個參數也可以兩個參數,必須的頭文件#include < algorithm>和using namespace std;
2、它使用的排序方法是類似於快排的方法,時間復雜度為n*log2(n)
3、Sort函數有三個參數:(第三個參數可不寫)
(1)第一個是要排序的數組的起始地址。
(2)第二個是結束的地址(最后一位要排序的地址)
(3)第三個參數是排序的方法,可以是從大到小也可是從小到大,還可以不寫第三個參數,此時默認的排序方法是從小到大排序
2個參數排序
sort(v.begin(), v.end());
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 int main() 5 { 6 int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 }, i; 7 for (i = 0; i<10; i++) 8 cout << a[i] << endl; 9 sort(a, a + 10); 10 for (i = 0; i<20; i++) 11 cout << a[i] << endl; 12 system("pause"); 13 return 0; 14 }
自定義fun排序
i>j 降序;
i<j 升序;
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 bool sfun(int i, int j){ 5 return i > j; 6 } 7 int main() 8 { 9 int a[20] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 }, i; 10 for (i = 0; i<20; i++) 11 cout << a[i] << endl; 12 sort(a, a + 20, sfun); 13 for (i = 0; i<20; i++) 14 cout << a[i] << endl; 15 system("pause"); 16 return 0; 17 }
結構體排序;
//需要用static
//2. sort中的比較函數compare要聲明為靜態成員函數或全局函數,不能作為普通成員函數,否則會報錯。 invalid use of non-static member function
//因為:非靜態成員函數是依賴於具體對象的,而std::sort這類函數是全局的,因此無法再sort中調用非靜態成員函數。
靜態成員函數或者全局函數是不依賴於具體對象的, 可以獨立訪問,無須創建任何對象實例就可以訪問。同時靜態成員函數不可以調用類的非靜態成員。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: static bool sfun(Interval a,Interval b){ return a.start<b.start; } void test (vector<Interval>& intervals) { sort(intervals.begin(),intervals.end(),sfun); } };