(C++)std::sort以及std::qsort用法(蓝桥杯序列排序)
sort用法
我们最常用的sort函数,sort函数有升序和降序,默认为升序
//默认用法(升序)#include<iostream>using namespace std;#include<algorithm>#include<cstdlib>int main(){ int n; cin >> n; int a[200]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a,a+n); for (int i = 0; i < n; i++) cout << a[i]<<" "; return 0;}
//一般用法(降序)#include<iostream>using namespace std;#include<algorithm>#include<cstdlib>bool compare(int a,int b){ return a>b;//如果改为 return a<b; 是升序}int main(){ int n; cin >> n; int a[200]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a,a+n,compare); for (int i = 0; i < n; i++) cout << a[i]<<" "; return 0;}
整合版:ASE是升序,DESC是降序
enum NumComp{ASE,DESC};//枚举出升降序变量 //创建一个类class compare {private: NumComp com;public://构造函数 compare(NumComp c) :com(c) {} bool operator()(int a, int b)// ()重载 { switch (com) { case ASE: return a < b; case DESC: return a > b; } }};int main(){ int n; cin >> n; int a[200]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n,compare(DESC));//改为ASE是升序 for (int i = 0; i < n; i++) cout << a[i] << " "; return 0;}
qsort用法
qsort升降序与compare函数有关,并且compare函数必须用户自己给出
#include <iostream>#include <cstdlib>using namespace std;int compare(const void *a, const void *b)//类型自定,double*,char*等{//升序 return *(int*)a - *(int*)b; // return *(int*)b-*(int*)a;降序}int main(){ int a[10] = { 5, 6, 4, 3, 7, 0, 8, 9, 2, 1 }; qsort(a, sizeof(a) / sizeof(a[0]), sizeof(int), compare); for (int i = 0; i < 10; i++) cout << a[i] << " " << endl; return 0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。