Sort用法

29 篇文章 0 订阅
25 篇文章 0 订阅

sort排序

包含在c++头文件<algorithm>

该函数包含三个参数

1.排序数组的起始地址

2.排序数组的结束地址

3.排序的顺序(升序(默认),降序(需要加一个比较函数,下列演示中加compare函数))

 升序演示

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
	int a[10];
	for(int i=0;i<=8;i++)
	cin>>a[i];
	//升序 
	sort(a,a+9);
	cout<<"升序结果为:" ; 
	for(int i=0;i<=8;i++)
	cout<<a[i]<<" ";
	return 0;
 } 

降序演示

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
/****用于降序排序的比较函数 *****/
bool cmy1(int a,int b)
{
 	return a>b;
}
int main()
{
	int a[10];
	for(int i=0;i<=8;i++)
	cin>>a[i];
	//降序
	sort(a,a+9,compare);
	cout<<endl<<"降序结果为:" ;
	for(int i=0;i<=8;i++)
	cout<<a[i]<<" ";
	return 0;
 } 

结构体排序

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
/*****自定义的结构体*******/ 
struct node{
	int a;
	int b;
	int c;
};
/***用于结构体的排序的比较函数******/ 
bool cmp2(node x,node y)
{
	if(x.a!=y.a)return x.a<y.a;//先按a升序 
	if(x.b!=y.b)return x.b>y.b;//a相同则按b降序
	return x.c>y.c; //b相同则按c降序 
}
int main()
{
	node nd[5];
	nd[0].a=1;nd[0].b=2;nd[0].c=3;
	nd[1].a=3;nd[1].b=2;nd[1].c=3;
	nd[2].a=3;nd[2].b=4;nd[2].c=1;
	nd[3].a=2;nd[3].b=4;nd[3].c=6;
	for(int i=0;i<=8;i++)
	//结构体排序,按a升序,按b降序,按c降序
	sort(nd,nd+4,cmp2);
	for(int i=0;i<=3;i++)
	cout<<nd[i].a<<"  "<<nd[i].b<<"  "<<nd[i].c<<endl;
	return 0;
 } 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值