数组一般的sort排序
#include<iostream>
#include<algorithm>
using namespace std;
int a[10]={
5,1,8,4,2,5,7,4,9,10};
int main(){
int i;
sort(a,a+10);
for(int i=0;i<10;i++){
cout<<a[i]<<" ";
}
return 0;
}
//输出:1 2 4 4 5 5 7 8 9 10
数组自定义使用cmp仿函数
#include<iostream>
#include<algorithm>
using namespace std;
int a[10]={
5,1,8,4,2,5,7,4,9,10};
//这里是从大到小排序
bool cmp(const int &a,const int&b){
return a>b;
}
int main(){
int i;
sort(a,a+10,cmp);
for(int i=0;i<10;i++){
cout<<a[i]<<" ";
}
return 0;
}
//输出:10 9 8 7 5 5 4 4 2 1 %
结构体排序
重载小于号有两种方式,作为类的成员函数,或者用友元friend,
作为成员函数时,有隐士的this指针,只有一个参数;
用friend友元时,没有this指针,用两个参数;
#include<iostream>

本文详细介绍了如何使用C++实现数组的普通排序、自定义排序函数,以及结构体的排序,包括优先队列的使用技巧。通过实例演示了如何根据特定规则调整排序,并针对不同场景如矩阵合并和最小元素查找进行了代码实现。
最低0.47元/天 解锁文章
427

被折叠的 条评论
为什么被折叠?



