STL里面的sort()函数使用结构体

当用sort()想对结构体进行排序的时候,这时候就需要自己写一个排序函数了

写这个是因为自己好久没用STL里面的sort()函数了。都忘记了 。再次实现一下

其实排序函数也很简单,自己实现

代码如下:

#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;

typedef struct index 
{
	int a,b;
}index;

bool cmp(index a , index b)
{
	if (a.a > b.a )
	{
		return true;
	}
	else
		if ( a.a == b.a  )
		{
			if (a.b > b.b )
			{
				return true ;
			}
		}
	return false ;
}

int main()
{
	index c[100];
	srand( time(0) );
	for (int i = 0 ; i < 100 ; ++i )
	{
		c[i].a = rand()%10 ; 
		c[i].b = rand()%10 ;
	}

	sort( c , c+100 , cmp );


	for (i = 0 ; i < 100 ; ++i )
	{
		cout<<c[i].a <<"   "<<c[i].b <<endl;
	}
	return 0;
}

 

排序顺序:

首先按照a递减的方式排序。

若a相同,则按照b的递减方式排序

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值