#include <algorithm>中sort的一般用法
来源:互联网 发布:mac下载百度云太慢 编辑:程序博客网 时间:2024/05/20 21:33
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; }
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; }
(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; } }
转载出处:http://blog.csdn.net/xiangle1993/article/details/24191075
阅读全文
0 0
- #include <algorithm>中sort的一般用法
- #include <algorithm>中sort的一般用法
- #include <algorithm>中sort的一般用法
- <algorithm.h>中sort对结构体排序的用法
- <algorithm.h>中sort对结构体排序的用法
- <algorithm> 中sort的使用
- #include<algorithm>中的sort算法
- algorithm中sort函数的使用
- STL: <algorithm>中 sort()
- algorithm中sort函数
- C语言中,#include的用法:#include "" 和 #include<>区别
- 【#include<algorithm>】中包含的可以直接调用的函数
- android中include的用法
- STL:algorithm中排序函数sort(升序排列函数)和reverse(反转排列函数)的简单用法
- #include<algorithm>里的函数
- #include<algorithm>里的函数
- #include<algorithm>里的函数
- #include<algorithm>里的函数
- Java中的堆和栈
- 【java面试题】2017.11.17
- java -- while循环拆分性能测试程序
- 数据库分库分表(sharding)(一)——基本思想、拆分策略和拆分所带来的问题
- JMeter源码导入到Intellij IDEA
- #include <algorithm>中sort的一般用法
- ES6_let
- 函数的调用Fact()
- memcache的工作原理
- 免费馅饼dp
- 01-复杂度2 Maximum Subsequence Sum
- LeetCode628. Maximum Product of Three Numbers 解题
- 自然语言处理研究内容的分支汇总
- using namespace std报错