C++涓璼ort鍑芥暟浣跨敤鏂规硶
C++涓璼ort鍑芥暟鏄敤鏉ュ瀹瑰櫒涓殑鍏冪礌杩涜鎺掑簭鐨勶紝瀹冪殑浣跨敤鏂规硶濡備笅锛?/p>
-
鍖呭惈澶存枃浠讹細
#include<algorithm>
-
瀹氫箟寰呮帓搴忕殑瀹瑰櫒锛屾瘮濡傛暟缁勩€佸悜閲忔垨鑰呭瓧绗︿覆銆?/p>
-
璋冪敤sort鍑芥暟锛?code>sort(first, last)锛屽叾涓?code>first鍜?code>last鍒嗗埆鏄鍣ㄧ殑璧峰杩唬鍣ㄥ拰缁撴潫杩唬鍣ㄣ€?/p>
-
sort鍑芥暟浼氭寜鐓ч粯璁ょ殑鍗囧簭瑙勫垯瀵瑰鍣ㄤ腑鐨勫厓绱犺繘琛屾帓搴忋€傚鏋滆鎸夌収闄嶅簭鎺掑簭锛屽垯闇€瑕佽嚜瀹氫箟姣旇緝鍑芥暟銆?/p>
渚嬪锛屽涓€涓暣鍨嬫暟缁勮繘琛屽崌搴忔帓搴忕殑绀轰緥浠g爜濡備笅锛?/p>
#include<algorithm>
#include<iostream>
int main() {
int arr[] = {5, 2, 8, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n);
for(int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
杈撳嚭缁撴灉涓猴細1 2 4 5 8
濡傛灉瑕佹寜鐓ч檷搴忔帓搴忥紝鍒欓渶瑕佽嚜瀹氫箟姣旇緝鍑芥暟锛屽苟灏嗗叾浣滀负sort鍑芥暟鐨勭涓変釜鍙傛暟浼犲叆銆?/p>
渚嬪锛屽涓€涓暣鍨嬫暟缁勮繘琛岄檷搴忔帓搴忕殑绀轰緥浠g爜濡備笅锛?/p>
#include<algorithm>
#include<iostream>
bool compare(int a, int b) {
return a > b;
}
int main() {
int arr[] = {5, 2, 8, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n, compare);
for(int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
杈撳嚭缁撴灉涓猴細8 5 4 2 1
相关问答