Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台

库函数 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

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

posted @ 2012-05-17 23:20  大嘴鸟  阅读(291)  评论(0编辑  收藏  举报
Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台