一、sort函数基础操作
1. 标准排序方法
#include <algorithm> #include <iostream> using namespace std; int main() { int arr[] = {5, 2, 8, 3, 1}; sort(arr, arr + 5); // 默认升序排序 for(int i=0;i<5;i++){ cout<<arr[i]<<" ";// 输出1 2 3 5 8 } return 0; }
2. 排序原理与特性
-
时间复杂度:O(NlogN) 的混合排序(快速排序+插入排序)
-
适用范围:支持随机访问的容器(数组、vector等)
-
稳定性:非稳定排序(等值元素可能改变原始顺序)
二、自定义排序规则精解
1. 基础比较函数
#include <algorithm>
#include <iostream>
using namespace std;
// 自定义排序规则
bool myCmp(char a,char b){
return a>b;
}
int main()
{
//按ascll码从大到小进行排序
char a[]={'1','A','a','c','D'};
sort(a,a+5,myCmp);
for(int i=0;i<5;i++){
cout<<a[i]<<" ";
}
return 0;
}
2. 结构体多条件排序
//2.1成绩数组 struct student { string name; int chinese; int math; }; // 2.2对总成绩进行降序排序 bool b(student x,student y) { int v1=x.chinese+x.math; int v2=y.chinese+y.math; if(v1>v2) //v1的总成绩大于v2的总成绩 return true; return false; } int main() { student s[1024]; int n; cin >>n; for(int i=0;i<n;i++) { cin >>s[i].name >>s[i].chinese >>s[i].math; s[i].classnum=s[i].chinese+s[i].math; } sort(s,s+n,b); for(int i=0;i<n;i++){ cout<<s[i].name<<endl; } return 0; }
三、排序常见问题解决方案
问题类型 | 解决方案 |
---|---|
自定义比较函数无效 | 检查返回值逻辑,确保严格弱序 |
结构体排序结果异常 | 验证所有排序条件的优先级顺序 |
性能瓶颈 | 优先使用移动语义,减少拷贝操作 |
稳定性要求 | 改用stable_sort保持相等元素顺序 |
复杂排序规则 | 使用tuple进行比较简化多条件判断 |