C++ sort()函数的用法秒懂
来源:互联网 发布:中级程序员工资待遇 编辑:程序博客网 时间:2024/06/05 14:15
刚学C语言还是C++的同学,喜欢ACM的同学,可能要接触一些类似OJ的做题系统,有时候排序可能有点慢,还很容易出错,接下来给大家介
绍系统自带的sort函数的用法。
头文件:
#include <algorithm>
using namespace std;
1.默认的sort函数是按升序排。对应于1
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2
① 升序排序
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);是对数组a降序排序
②int cmp( const int &a, const int &b )
{
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp); 是对数组a降序排序
③int cmp( const POINT &a, const POINT &b )
{
if( a.x < b.x )
return 1;
else if( a.x == b.x )
{
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp); 是先按x升序排序,若x值相等则按y升序排
④更方便的是用反转函数reverse
reverse(a,a+n)反转数组变成降序
可能你会遇到一种题目,两个数组的对应的,一个进行排序然后一个跟着排序一一对应
struct task
{
int x,y,z;
};//定义结构体,让两个数组同在一个结构中
bool cmp(task a,task b)
{
return a.y>b.y;
}
sort(c,c+n,cmp);
//结构体数组一般用qsort比较好用。
本人也是初识这些知识,部分知识转载,希望对大家有所帮助。
绍系统自带的sort函数的用法。
头文件:
#include <algorithm>
using namespace std;
1.默认的sort函数是按升序排。对应于1
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2
① 升序排序
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);是对数组a降序排序
②int cmp( const int &a, const int &b )
{
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp); 是对数组a降序排序
③int cmp( const POINT &a, const POINT &b )
{
if( a.x < b.x )
return 1;
else if( a.x == b.x )
{
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp); 是先按x升序排序,若x值相等则按y升序排
④更方便的是用反转函数reverse
reverse(a,a+n)反转数组变成降序
可能你会遇到一种题目,两个数组的对应的,一个进行排序然后一个跟着排序一一对应
struct task
{
int x,y,z;
};//定义结构体,让两个数组同在一个结构中
bool cmp(task a,task b)
{
return a.y>b.y;
}
sort(c,c+n,cmp);
//结构体数组一般用qsort比较好用。
本人也是初识这些知识,部分知识转载,希望对大家有所帮助。
0 0
- C++ sort()函数的用法秒懂
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort()函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort函数的用法
- C++sort()函数的用法
- C++sort()函数的用法
- C++sort函数的用法
- c++sort函数的用法
- C++sort 函数用法
- C++sort 函数用法
- 《您的设计模式》(CBF4LIFE)之“组合模式”【整理】
- 12.27
- AR摄像机不能聚焦问题的解决办法
- bzoj1306(搜索与剪枝经典)
- 你应该知道的 RPC 原理
- C++ sort()函数的用法秒懂
- VIPServer:阿里智能地址映射及环境管理系统详解
- 多台CentOS服务器时间同步(NTP时间同步)
- FileInputStream,FileOutputStream,FileReader,FileWriter,BufferedReader,BufferedWriter相关的IO技术
- Leetcode-137. Single Number II
- AR摄像机不能聚焦问题的解决办法
- 微信公共號開發學習資料
- passwd文件意义与ls-l的含义
- Android计算器项目