sort函数
来源:互联网 发布:淘宝店铺可以转吗 编辑:程序博客网 时间:2024/06/08 08:57
MSDN中的定义:
template<class RanIt>
void sort(RanIt first, RanIt last); //--> 1)
template<class RanIt, class Pred>
void sort(RanIt first, RanIt last, Pred pr); //--> 2)
头文件:
#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 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升序排
与此类似的还有C中的qsort,以下同附上qsort的使用方法:
#include <stdlib.h>
格式 qsort(array_name,data_number,sizeof(data_type),compare_function_name) (void*)bsearch (pointer_to_key_word,array_name,find_number,
sizeof(data_type),compare_function_name)
e.g.
int Cmp(const void*a,const void *b)
{
int*pa=(int*)a,*pb=(int*)b;
if(*pa>*pb) return 1;
else if (*pa==*pb) return 0;
else return -1;
}
qsort(data,N,sizeof(int),Cmp); // 对int型数组进行快速排序(非降序排列)
p=(int*)bsearch(&a,data,n,sizeof(int),Cmp);
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort 函数
- sort函数
- sort函数
- sort()函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- C语言的指针
- SpringMVC的工作流程
- 浅谈安全模式
- hdu 1851 A Simple Game
- hdu 4004 贪心 二分查找
- sort函数
- Java数据结构07----队列:顺序队列&顺序循环队列、链式队列、顺序优先队列
- 火狐浏览器安装firebug方式
- 学习笔记 --- LINUX网卡驱动框架分析
- 20170816_二叉树的建立+前序遍历+中序遍历+后序遍历+层序遍历
- 软测概述
- 海量数据处理面试题
- 数据库
- (4)nodejs学习---自定义模块