stl中sort函式詳解
阿新 • • 發佈:2018-12-31
1. sort 函式的形式:
②採用函式指標的形式,這裡第三個引數只需要寫出自己在外邊定義的函式名稱即可。
③採用比較器(函式運算子)的形式,事實上c++提供的這種函式運算子從某種意義上來講就是取代c語言中中的函式指標。而且比它更靈活,因為自己可以定義自己所需要的規則。
sort(first_pointer,first_pointer+n,cmp)
函式的第一個引數是陣列的首地址,一般寫上陣列名就可以,因為陣列名是一個指標常量。第二個引數相對較好理解,即首地址加上陣列的長度n。最後一個引數是比較函式的名稱(一般比較函式名字都用cmp,當然這個名字是什麼都所謂),這個比較函式可以不寫,即第三個引數可以預設。此時sort預設按陣列升序排序。
2. 應用舉例
#include<iostream> #include<vector> #include<algorithm> using namespace std; template<typename iterator> void print(iterator begin,iterator end) { while(begin!=end) cout << *begin++ << ' '; cout << endl; } bool cmpInt(const int &a,const int &b) { return a<b; } class CmpInt { public: CmpInt(bool result=true):m_result(result){} bool operator()(const int &a,const int &b)const { return m_result?(a>b):(a<b); } private: bool m_result; }; int main() { int a[5]= {50,10,20,30,60}; vector<int>vi (a,&a[5]);//用陣列來初始化vector print(vi.begin(),vi.end()); // sort(vi.begin(),vi.end());//① // sort(vi.begin(),vi.end(),cmpInt); //② sort(vi.begin(),vi.end(),CmpInt(false));//③ print(vi.begin(),vi.end()); return 0; }
解析:
①用的是兩個引數的sort版本②採用函式指標的形式,這裡第三個引數只需要寫出自己在外邊定義的函式名稱即可。
③採用比較器(函式運算子)的形式,事實上c++提供的這種函式運算子從某種意義上來講就是取代c語言中中的函式指標。而且比它更靈活,因為自己可以定義自己所需要的規則。