sort();对结构体数组的排序

sort(); 位于C++ 

头文件 #include<algorithm>中

数组排序(从小到大,从大到小)

结构体排序(数字参数从大到小...字符串为参数 字典序....)

代码示例:(直接复制运行对比结果看源码)

#include<iostream>

#include<algorithm>

using namespace std;
// 对下文所有函数进行声明

struct node
{
  int sum;
  char s[10];
} str[10];


int cmpn1(node a,node b)
{
  return a.sum>b.sum;
}


int cmpn2(node a,node b)
{
  return a.s>b.s;
}


int cmp(int a,int b)
{
  return a>b;
}

int main()
{
  int a[100]= {1,3,6,9,4,2,3,6,7,10};
  //一共10个
  cout<<"a数组最初状态\n"<<endl;
  for(int i=0; i<10; i++)
    cout<<a[i]<<endl;
  //需要排序首位置加上需排序的位长
  cout<<"默认是从大到小排序\n"<<endl;
  sort(a,a+10);
  for(int i=0; i<10; i++)
    cout<<a[i]<<endl;
  cout<<endl;
  cout<<"引入cmp()从大到小\n"<<endl;
  sort(a,a+10,cmp);
  for(int i=0; i<10; i++)
    cout<<a[i]<<endl;
  cout<<endl;
  // 结构体赋值
  for(int i=0; i<10; i++)
  {
    str[i].sum=i;
    str[i].s[0]='a'+i;
  }
  cout<<"以sum为参数 调用cmp1进行从大到小\n"<<endl;
  sort(str,str+10,cmpn1);
  for(int i=0; i<10; i++)
    cout<<str[i].sum<<endl;
  cout<<endl;
  cout<<"经过sum作为参数排序后,字符串目前状态\n"<<endl;
  for(int i=0; i<10; i++)
    cout<<str[i].s<<endl;
  cout<<endl;
  cout<<"以s为参数 调用cmp2进行字典序\n"<<endl;
  sort(str,str+10,cmpn2);
  for(int i=0; i<10; i++)
    cout<<str[i].s<<endl;
  cout<<endl;

  return 0;

}

转载于:https://www.cnblogs.com/maxv/p/10548750.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值