C++sort函数的用法
2015-06-08 21:23
429 查看
MSDN中的定义:
template<class RanIt> void sort(RanIt first, RanIt last); //--> 1) t emplate<class RanIt, class Pred> void sort(RanIt first, RanIt last, Pred pr); //--> 2)
Sorts the elements in the range [first,last) into ascending order. The elements are compared using operator< for the first version, and comp for the second. Equivalent elements are not guaranteed to keep their original relative order (see stable_sort).
<pre name="code" class="cpp">[first,last) Random-access iterators to the initial and final positions of the sequence to be sorted. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. RandomAccessIterator shall point to a type for which swap is properly defined and which is both move-constructible and move-assignable.
头文件:
#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);
#include <iostream> #include <algorithm> //这个是包含sort函数的头文件 using namespace std; int arr[100], n; int cmp(int x, int y){ //这个函数是sort函数比较两个元素优先级的函数,在这里计算出两个元素的优先级,然后返回即可 //此处插入代码计算x,y的重要性 return x < y; //此处返回小于号,意思是优先级小的在前面,如return x<y; 则数组会由小达到排序 } int main(){ cin>>n; for(int i = 0; i < n; i++) cin>>arr[i]; sort(arr, arr + n, cmp); cout<<"after sort: "<<endl; for(int i = 0; i < n; i++) cout<<arr[i]<<" "; return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- Linux Shell - 如何使用sort与uniq命令删除重复的文本行
- share_ptr的几个注意点
- 文件遍历排序函数
- C#选择排序法实例分析
- C#插入法排序算法实例分析
- 批处理命令教学之字符串排序(sort)
- Lua教程(一):在C++中嵌入Lua脚本
- C#实现Datatable排序的方法
- Lua教程(二):C++和Lua相互传递数据示例
- SQLSERVER的排序问题结果不是想要的
- Windows Powershell排序和分组管道结果
- C#通过IComparable实现ListT.sort()排序
- C#选择法排序实例分析
- SQL学习笔记四 聚合函数、排序方法
- C++联合体转换成C#结构的实现方法
- C#对list列表进行随机排序的方法
- 一根网线内的8根线哪4根是传输数据的,哪四根是防干扰的