#include <algorithm>中sort的一般用法
2024-10-14 17:20:26
1、sort函数的时间复杂度为n*log2(n),执行效率较高。
2、sort函数的形式为sort(first,end,method)//其中第三个参数可选。
3、若为两个参数,则sort的排序默认是从小到大,见如下例子
- #include<iostream>
- #include<algorithm>
- using namespace std;
- int main()
- {
- int a[10]={9,6,3,8,5,2,7,4,1,0};
- for(int i=0;i<10;i++)
- cout<<a[i]<<endl;
- sort(a,a+10); //可以看出,两个参数为均地址,a为起始,a+10为结束位置
- for(int i=0;i<10;i++)
- cout<<a[i]<<endl;
- return 0;
- }
#include<iostream> #include<algorithm> using namespace std; int main() { int a[10]={9,6,3,8,5,2,7,4,1,0}; for(int i=0;i<10;i++) cout<<a[i]<<endl; sort(a,a+10); //可以看出,两个参数为均地址,a为起始,a+10为结束位置 for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0; }
4、若为三个参数,则需要写一个cmp函数(此名称cmp可变),用于判断是从小到大排序还是从大到小排序。
(1)需要排序的数组直接为int类型,则见如下例子(从大到小排序)
- #include <algorithm>
- #include <iostream>
- using namespace std;
- bool com(int a,int b)
- {
- return a>b;
- }
- int main()
- {
- int a[10]={9,6,3,8,5,2,7,4,1,0};
- for(int i=0;i<10;i++)
- cout<<a[i]<<endl;
- sort(a,a+10,com);//在这里就不需要对com函数传入参数
- for(int i=0;i<10;i++)
- cout<<a[i]<<endl;
- return 0;
- }
#include <algorithm>
#include <iostream>
using namespace std; bool com(int a,int b) { return a>b; } int main() { int a[10]={9,6,3,8,5,2,7,4,1,0}; for(int i=0;i<10;i++) cout<<a[i]<<endl; sort(a,a+10,com);//在这里就不需要对com函数传入参数 for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0; }
(2)如果想依照一个结构体内的一个int型的属性参数进行排序,则见如下例子(从大到小排列)
- #include <iostream>
- #include <algorithm>
- using namespace std;
- struct node {
- int a;
- //.........
- //
- };
- bool cmp(node x,node y)
- {
- if(x.a != y.a)
- return (x.a > y.a);
- }
- void main(void)
- {
- int i;
- node N_t[5];
- for(i=0; i<5; i++)
- {
- cin>>N_t[i].a;
- }
- sort(N_t, N_t+5, cmp);
- for(i=0; i<5; i++)
- {
- cout<<N_t[i].a;
- }
- }
最新文章
- 关于Hadoop的集群环境下虚拟机采用NAT方式连不上网的解决
- XtraReport 添加空行的办法,很详细
- jQuery基础(2)-- jQuery 选择器
- linux与windows的文本文件之间的转换
- Zend Framework 入门(3)—错误处理
- Matplotlib下载地址
- mongdb单节点安装方法
- tar、scp、sftp、rsync简单使用
- PyCharm 2018 永久激活
- SpringCloud系列十二:SpringCloudSleuth(SpringCloudSleuth 简介、SpringCloudSleuth 基本配置、数据采集)
- MyBatis源码解析(一)——执行流程
- elastic-job详解(五):自定义任务参数
- 如何在linux下开启FTP服务
- 周强 201771010141《面向对象程序设计(java)》第四周学习总结
- Vue.js hello world
- 开发中遇到的一些mongoose的问题
- 【Git】四、Git工作
- HDU 5703
- Ubuntu14.04系统下无法连接Wi-Fi无线网以及安装BCM43142网卡驱动的解决方案
- 转载文章 MySQL与Oracle的区别
热门文章
- Fail Fast and Fail Safe Iterators in Java
- windows执行命令来运行loadrunner录制好的脚本(收藏)
- history设置时间戳
- Android UI-实现底部切换标签(fragment)
- 实现ScrollviewSupportMaxHeight
- 【LeetCode】55. Jump Game
- 如何实现IOS_SearchBar搜索栏及关键字高亮
- How to develop and deploy ActiveX control in C#
- iOS - Contacts 通讯录
- BIP_BI Pubisher的SQL/XSL/FO扩展函数应用(概念)