现在的位置: 首页 > 综合 > 正文

sort algorithm

2019年04月26日 ⁄ 综合 ⁄ 共 575字 ⁄ 字号 评论关闭

MSDN中的定义:
1.template<class RanIt>                         void sort(RanIt first, RanIt last); 
2.template<class RanIt, class Pred>    void sort(RanIt first, RanIt last, Pred pr); 
头文件:
#include <algorithm>
using namespace std;

1.默认的sort函数是按升序排。对应于1
sort(a,a+n);   //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2
例如:是对数组a降序排序
int cmp( const int &a, const int &b )
{
    if( a > b )
       return 1;
    else
       return 0;
}
sort(a,a+n,cmp);
又如:
是先按x升序排序,若x值相等则按y升序排
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);

抱歉!评论已关闭.