您的位置:首页 > 编程语言 > C语言/C++

C++sort函数的用法

2015-06-08 21:23 435 查看


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++ 排序 sort