C++ sort()函数的用法秒懂

来源:互联网 发布:中级程序员工资待遇 编辑:程序博客网 时间:2024/06/05 14:15
刚学C语言还是C++的同学,喜欢ACM的同学,可能要接触一些类似OJ的做题系统,有时候排序可能有点慢,还很容易出错,接下来给大家介


绍系统自带的sort函数的用法。
头文件:
#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 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升序排
④更方便的是用反转函数reverse
reverse(a,a+n)反转数组变成降序






可能你会遇到一种题目,两个数组的对应的,一个进行排序然后一个跟着排序一一对应
struct task
{
    int x,y,z;
};//定义结构体,让两个数组同在一个结构中
bool cmp(task a,task b)
{
    return a.y>b.y;
}
sort(c,c+n,cmp);
//结构体数组一般用qsort比较好用。




本人也是初识这些知识,部分知识转载,希望对大家有所帮助。



0 0