C++ sort用法
阿新 • • 發佈:2018-12-02
標頭檔案:#include <algorithm>
例如:int a[10]={5,6,3,4,1,18,34,23,56,15};
執行sort(a,a+10); 則陣列a中的元素將進行升序排序。
另外,可自定義返回型別為bool型的compare函式,指定sort的排序方式。
bool compare(int a,int b)
{
return a>b;
}
sort(a,a+10,compare)可對陣列a進行降序排序。
測試程式碼如下:
#include <iostream> #include <algorithm> using namespace std; bool compare(int a, int b) { return a > b; } int main() { int a[10] = { 5, 6, 3, 4, 1, 18, 34, 23, 56, 15 }; int i; sort(a, a + 10); for (int i = 0; i < 10; i++) { cout << a[i] << " "; } cout << endl; sort(a, a + 10, compare); for (int i = 0; i < 10; i++) { cout << a[i] << " "; } cout << endl; return 0; }
測試結果如下: