定义sort函数---strcmp()用法-----案例7-1.1 模拟EXCEL排序 (25分)

Excel可以对一组纪录按任意指定列排序。现请编写程序实现类似功能。

输入格式:
输入的第一行包含两个正整数N(≤10
​5
​​ ) 和C,其中N是纪录的条数,C是指定排序的列号。之后有 N行,每行包含一条学生纪录。每条学生纪录由学号(6位数字,保证没有重复的学号)、姓名(不超过8位且不包含空格的字符串)、成绩([0, 100]内的整数)组成,相邻属性用1个空格隔开。

输出格式:
在N行中输出按要求排序后的结果,即:当C=1时,按学号递增排序;当C=2时,按姓名的非递减字典序排序;当C=3时,按成绩的非递减排序。当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。

输入样例:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

输出样例:
000001 Zoe 60
000007 James 85
000010 Amy 90

strcmp()

The strcmp() compares two strings character by character.

If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of two strings are different or a null character ‘\0’ is reached.

It is defined in the string.h header file.

Return Value from strcmp()
Return Value Remarks
0 if both strings are identical (equal)
negative if the ASCII value of the first unmatched character is less than second.
positive integer if the ASCII value of the first unmatched character is greater than second.

AC代码:

//自定义sort函数
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAX 100005
using namespace std;
struct node{
    int x;
    char name[15];
    int y;
}p[MAX];
int n,c;
bool cmp(const node& x1,node& x2){        //当C=1时,按学号递增排序
        return x1.x<x2.x;
}
bool cmp1(const node& x3,const node& x4){        //当C=2时,按姓名的非递减字典序排序,当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。
    if(strcmp(x3.name,x4.name)==0){return x3.x<x4.x;}
    return strcmp(x3.name,x4.name)<0;
}
bool cmp2(const node& x5, const node& x6){        //当C=3时,按成绩的非递减排序
    if(x5.y==x6.y){return x5.x<x6.x;}
    return x5.y<x6.y;
}
int main(){
    cin>>n>>c;
    int i=0;
    while(i<n){
        scanf("%d %s %d",&p[i].x,p[i].name,&p[i].y);
        i++;
    }
    if(c==1){sort(p,p+n,cmp);}
    if(c==2){sort(p,p+n,cmp1);}
    if(c==3){sort(p,p+n,cmp2);}
    for(int i=0;i<n;i++){
        printf("%06d %s %d\n",p[i].x,p[i].name,p[i].y);
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值