轉載於:http://www.cnblogs.com/luorende/p/6121906.html
STL中就自帶了排序函數sortsort 對給定區間所有元素進行排序 要使用此函數只需用#include <algorithm> sort即可使用,語法描述為:
//sort(begin,end),表示一個范圍,例子: #include <algorithm> int main() { int a[20]={2,4,1,23,5,76,0,43,24,65},i; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }
輸出結果將是把數組a按升序排序,說到這里可能就有人會問怎么樣用它降序排列呢?這就是下一個討論的內容.
一種是自己編寫一個比較函數來實現,接着調用三個參數的sort:sort(begin,end,compare)就成了。對於list容器,這個方法也適用,把compare作為sort的參數就可以了,即:sort(compare).
1)自己編寫compare函數:
#include <algorithm> bool compare(int a,int b) { return a<b; //升序排列,如果改為return a>b,則為降序 } int main() { int i; int a[20]={2,4,1,23,5,76,0,43,24,65}; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20,compare); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }