结构体快排回顾(sort)

一般来说,我做竞赛的时候排序一般用快排

很快很方便

普通sort(从小到大)

sort(a,a+n);

直接贴一段代码吧,包含了vector,sort,结构体等简单东西综合

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct example
{
    int elem1;
    int elem2;
}example;

/*这个comparison函数很重要.如果希望升序排序,就是"<",降序排列就是">"号,这样便于直观记忆.如果希望用elem2作为比较标准
就把elem1改为elem2,这样结构体就以elem2为比较标准排序了.*/
bool comparison(example a,example b){
    return a.elem1<b.elem1;
}

int main()
{
    int N;
    fin>>N;

    vector<example> array(N);

    for(int i=0;i<N;i++)
    {
        fin>>array[i].elem1>>array[i].elem2;
    }

    sort(array.begin(),array.end(),comparison);

    for(int i=0;i<N;i++)
    {
        cout<<array[i].elem1<<" "<<array[i].elem2<<endl;
    }
        return 0;
}

  

再搞一段

#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;
}

  

转载于:https://www.cnblogs.com/SSYYGAM/p/6090716.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值