• 用法一:数组排序

对一个数组进行升序排序

#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());
 

最新文章

  1. 字典树+博弈 CF 455B A Lot of Games(接龙游戏)
  2. js基础
  3. URL、Session、Cookies、Server.Transfer、Application和跨页面传送,利弊比较
  4. android 回调函数二:应用实例
  5. AngularJS 学习随笔(一)
  6. 【HDOJ】4210 Su-domino-ku
  7. nginx详细配置文件 (转)
  8. spring core源码解读之ASM4用户手册翻译之一asm简介
  9. Powershell错误处理,try catch finally
  10. vs2008工程配置
  11. Memcached简明介绍
  12. 牛腩公布系统--HTTP 错误 403.14 - Forbidden
  13. ios 初体验&lt;真机调试&gt;
  14. 基于 angular 规范的 commit
  15. JavaScript大师必须掌握的12个知识点
  16. go语言之进阶篇普通变量的方法集
  17. NS-3 MyFirstScriptExample
  18. go语言进阶之为结构体类型添加方法
  19. C++笔记 5
  20. 设计一个学生类&amp;班级类

热门文章

  1. Java高级项目实战03:CRM系统数据库设计
  2. kali中安装中文输入法ibus
  3. linux中文件处理命令
  4. Python3标准库:functools管理函数的工具
  5. Girlfreind:1 Vulnhub Walkthrough
  6. VUE中使用XLSX实现导出excel表格
  7. Prime_Series_Level-1
  8. 探究Redis两种持久化方式下的数据恢复
  9. 展讯平台uboot启动流程
  10. go并发版爬虫