如何使用C語言中的sort函數(shù)
--- 頭文件在C語言中,STL庫(kù)中的sort函數(shù)可以用來對(duì)數(shù)組進(jìn)行排序。為了使用sort函數(shù),首先需要正確地引入頭文件??梢允褂萌f能頭文件 `include ` 來包含所需的頭文件信息。 函數(shù)語法s
---
頭文件
在C語言中,STL庫(kù)中的sort函數(shù)可以用來對(duì)數(shù)組進(jìn)行排序。為了使用sort函數(shù),首先需要正確地引入頭文件??梢允褂萌f能頭文件 `include 
函數(shù)語法
sort函數(shù)的基本語法如下:
- 當(dāng)參數(shù)缺省時(shí),函數(shù)原型為:`void sort(first, last);`,其中`first`是未排序數(shù)組的第一個(gè)元素,`last`是未排序數(shù)組的最后一個(gè)元素。默認(rèn)以遞增的順序排序。
- 一般形式為:`void sort(first, last, comp);`,多了一個(gè)比較函數(shù)`comp`,可以按照自定義的方式進(jìn)行排序。
比較函數(shù)缺省的排序
```cpp
include 
using namespace std;
int main() {
int a[] {4, 2, 3, 1, 2};
int n sizeof(a) / sizeof(int);
// 打印未排序數(shù)組
cout << "unsorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
// 排序
sort(a, a 4);
// 打印已排序數(shù)組
cout << "sorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
}
```
排序結(jié)果
未排序數(shù)組:4 2 3 1 2
已排序數(shù)組:1 2 3 4 5
不缺省,遞減排序
如果想按照遞減的順序排序,可以使用內(nèi)置的`greater
```cpp
include 
using namespace std;
int main() {
int a[] {4, 2, 3, 1, 2};
int n sizeof(a) / sizeof(int);
// 打印未排序數(shù)組
cout << "unsorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
// 遞減排序
    sort(a, a   4, greater
// 打印已排序數(shù)組
cout << "sorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
}
```
不缺省,自定義比較函數(shù)
除了使用內(nèi)置的比較函數(shù)外,還可以自定義比較函數(shù)來實(shí)現(xiàn)排序。例如,以下示例中的`compare`函數(shù)可實(shí)現(xiàn)升序排序:
```cpp
include 
using namespace std;
int compare(int a, int b) {
return a > b;
}
int main() {
int a[] {4, 2, 3, 1, 2};
int n sizeof(a) / sizeof(int);
// 打印未排序數(shù)組
cout << "unsorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
// 使用自定義比較函數(shù)排序
sort(a, a 4, compare);
// 打印已排序數(shù)組
cout << "sorted array: ";
for (int i 0; i < n; i )
cout << a[i] << " ";
cout << endl;
}
```
通過合理地使用C語言中的sort函數(shù),可以輕松對(duì)數(shù)組進(jìn)行排序,提高編程效率和代碼質(zhì)量。