C++sort函数的用法

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值