c++自带排序函数,不用直接去写些什么冒泡排序,快排什么的了,这就是面向对象的好处啊。至于这个sort函数怎么用,请往下看
sort函数在头文件#include<algorithm>里面,详细用法请看代码
#include<iostream> #include<algorithm> using namespace std; int main() { int n,a[10000]; cin>>n; for(int j=0;j<n;j++) cin>>a[j]; sort(a,a+n);//只对a[0]到a[n-1]进行升序排序,区间是左闭右开 for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
如何才能进行降序排序了?
1.自己写个比较函数cmp,代码如下:
#include<iostream> #include<algorithm> using namespace std; bool cmp( int m,int n ){ //比较函数 return m>n ; } int main() { int n,a[10000]; cin>>n; for(int j=0;j<n;j++) cin>>a[j]; sort(a,a+n,cmp); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
2.暂无,因为我还不会,等以后会了补上。。。
3.结构体学生成绩与姓名排序
bool cmp(struct student &a,struct student &b){ if(a.score>=b.score){ if(a.score==b.score){ return a.name<b.name } return a.score>b.score; } return false; }