c++中sort基础用法
2024-09-04 05:12:21
- 用法一:数组排序
对一个数组进行升序排序
#include <algorithm>
#include <iostream>
#include <cstdio> using namespace std; int main()
{
int a[]={,,,,,};
sort(a,a+);
for(int i=;i<;i++){
printf("%d ",a[i]);
}
return ;
}
sort包含在#include<algorithm>中,sort(数组头,数组尾),sort(a,a+6)可以看作sort(a+0,a+6)表示对数组a的第0个元素到第5个元素进行排序。默认排序方式为升序排序。
如果想进行降序排序则需要引入自定义排序规则compare
#include <algorithm>
#include <iostream>
#include <cstdio> using namespace std;
bool compare(int a,int b){
return a>b;
}
int main()
{
int a[]={,,,,,};
sort(a,a+,compare);
for(int i=;i<;i++){
printf("%d ",a[i]);
}
return ;
}
- 用法2:结构体排序
有时我们会遇到这样的问题,按学生成绩进行降序排序,如果成绩相同按学号升序排序,怎么用sort解决这个问题呢?
struct student{
int num; //学号
int score; //成绩
}; bool cmp(student a,student b){//按成绩降序,再按学号升序
if(a.score>b.score)return a.num<b.num;
return a.score>b.score;
} struct student stu[];
//输入学生数据
sort(a,a+,cmp);
- 用法3:动态数组vector内的排序
vector<int>s;
sort(s.begin(),s.end());
最新文章
- 字典树+博弈 CF 455B A Lot of Games(接龙游戏)
- js基础
- URL、Session、Cookies、Server.Transfer、Application和跨页面传送,利弊比较
- android 回调函数二:应用实例
- AngularJS 学习随笔(一)
- 【HDOJ】4210 Su-domino-ku
- nginx详细配置文件 (转)
- spring core源码解读之ASM4用户手册翻译之一asm简介
- Powershell错误处理,try catch finally
- vs2008工程配置
- Memcached简明介绍
- 牛腩公布系统--HTTP 错误 403.14 - Forbidden
- ios 初体验<;真机调试>;
- 基于 angular 规范的 commit
- JavaScript大师必须掌握的12个知识点
- go语言之进阶篇普通变量的方法集
- NS-3 MyFirstScriptExample
- go语言进阶之为结构体类型添加方法
- C++笔记 5
- 设计一个学生类&;班级类