库函数 sort 的用法

听了zzy,和鑫固的讲解 ,自己在写一遍sort,加深一下印象~~

注意 如果对 排序 a[0],a[10]     sort(a,a+10);

                      a[1],a[10]     sort(a+1,a+1+10);

                 a[0]  a[n]       sort(a,a+n);

                 a[1]   a[n]    sort(a+1,a+n+1);

 

 

注意 sort是在c++中使用

需要头文件 #include<algorithm>

               #include<iostream.h>

              using namespace std;

这样就可以使用了~!~

如果直接使用的话是从小到大排序~~~

post code:

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
  int i;
  int a[10]={1,2,3,4,5,6,7,8,9,0};
   sort(a,a+10);                               //从小到大排序
  for(i=0;i<10;i++)
  cout<<a[i]<<endl;
}

 

如果要从大到小排序直接使用

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)                       //定义一个函数就可以了~~~
{
return a>b;                                   //如果是>号的话是从大到小 反之是从小到大
}

int main()
{
  int i;
  int a[10]={1,2,3,4,5,6,7,8,9,0};
  sort(a,a+10,cmp);
  for(i=0;i<10;i++)
  cout<<a[i]<<endl;
}

 

关键是它对结构体的排序

#include<iostream>
#include<algorithm>
using namespace std;

struct node {
char x,y;

              }point[3]={'x','y','x','z','a','y'};

 
bool cmp(struct node a,struct node b)
{
    if(a.x!=b.x)return a.x<b.x;
    else return a.y<b.y;
}

int main()
{
    int i;
    sort(point,point+3,cmp);
    for(i=0;i<3;i++)
    cout<<point[i].x<<" "<<point[i].y<<endl;
}

得到的结果是 a,y  x,y  x,z

是按这样的排序来进行的~~~

原文链接: https://www.cnblogs.com/ysh-blog/archive/2012/05/17/2507010.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    库函数 sort 的用法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/50487

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午2:07
下一篇 2023年2月9日 上午2:08

相关推荐