std::sort的妙用(1)

有时候需要按照结构体中某项数值进行排序,而结构体中的其他数值则不能改变。例如,按照成绩的高低对学生进行排序,而学生这一结构体中包含了学号,姓名等其他信息。使用std::sort就很方便

CODE

struct edge{ int from, to, cost; };
bool comp(const edge &e1, const edge &e2)
{
	return e1.cost < e2.cost;
}
void sortFun()
{
	edge es[MAXVEX];
	srand((unsigned)time(NULL));
	int N = 9;
	for (int i = 0; i < N; ++i)
	{
		es[i].from = i;
		es[i].to = rand() % 9;
		es[i].cost = rand() % 28;
	}
	for (int i = 0; i < N; ++i)
	{
		printf("%d %d %d\n", es[i].from, es[i].to, es[i].cost);
	}
	printf("************************\n");
	sort(es, es + N, comp);
	for (int i = 0; i < N; ++i)
	{
		printf("%d %d %d\n", es[i].from, es[i].to, es[i].cost);
	}
	
}


#include<stdio.h>
#include<stdlib.h>
#include <cstring>
#include <cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

struct t_stu {
    int age;
    int score;
    char name[104];
};
  
inline bool Cmp(const t_stu & a, const t_stu & b){
    if(a.score == b.score){
        if(strcmp(a.name, b.name) == 0){
            return a.age > b.age;
        }
        return strcmp(a.name, b.name) > 0;
    }
    return a.score > b.score;
}
  
int main(void){
  
    int n;
    t_stu tStuRec[1001], *tp;

    while(~scanf("%d", &n))//注意输入,OJ常用
        {
        
         for(tp = tStuRec; n--; ++tp){
            scanf("%s %d %d", tp->name, &tp->age, &tp->score);
        }
  
        sort(tStuRec, tp, Cmp);
  
        while(--tp >= tStuRec){
            printf("%s %d %d\n", tp->name, tp->age, tp->score);
        }
    }
       
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值