刷题日记——国家名称排序

7.国家名称排序

在这里插入图片描述

分析

一开始打算用二维的字符数组来操作,但是数组指针玩不太明白,于是改用结构体,结构体country里面仅一个成员name(字符数组),这样就有两种解题方法:

方法一:使用sort排序

  • 创建一个country数组cry,大小为101(因为n最大为100)
  • 输入的国家名称放到country数组cry元素对应的name属性里面
  • 使用sort对country数组cry进行排序,注意,传入的三个参数如下,分别为country数组的首指针、尾后指针和排序函数名cmp
		sort(&cry[0], &cry[n], cmp);
  • 关于cmp函数的编写,是基于sort函数的特性,即两个待排的元素a,b,注意a和b都是country类型的,
    • 如果cmp(a,b)的值是true则不交换顺序,如果是false则交换顺序,
    • 再基于本题的要求,按照strcmp(a.name,b.name)判断字符串的大小即可,
      • 如果a.name的字母序数大于b.name,那么strcmp(a.name,b.name)值为正数
      • 如果a.name的字母序数小于或等于b.name,那么strcmp(a.name,b.name)值为负数或0
    • 那么,就应该在a.name的字母序数小于或等于b.name的时候,让cmp函数返回true,表示不用交换,否则就要交换。
方法一::使用sort排序(代码)
#include <cstdio>
#include <queue>
#include <cmath>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;

struct country {
	char name[50];
};

country cry[101];

bool cmp(country a, country b) {
	if (strcmp(a.name, b.name) <= 0) {
		return true;
	} else {
		return false;
	}
}

int main() {
	int n;

	while (scanf("%d", &n) != EOF) {
		for (int i = 0; i < n; i++) {
			scanf("%s", cry[i].name);
		}
		sort(&cry[0], &cry[n], cmp);
		for (int i = 0; i < n; i++) {
			printf("%s\n", cry[i].name);
		}
	}

	return 0;
}

方法二:使用优先队列

优先队列是大根堆,为了满足要求,需要对<符号进行重载,改写的方式与方法一使用sort函数时写得cmp函数思想类似。

方法二::使用优先队列(代码)
#include <cstdio>
#include <queue>
#include <cmath>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;

struct country {
	char name[50];
};

priority_queue<country> cry;

bool operator <(country a, country b) {
	if (strcmp(a.name, b.name) <= 0) {
		return false;
	} else {
		return true;
	}
}
int main() {
	int n;
	while (scanf("%d", &n) != EOF) {
		for (int i = 0; i < n; i++) {
			country temp;
			scanf("%s", temp.name);
			cry.push(temp);
		}
		while (cry.empty() != true) {
			printf("%s\n", cry.top().name);
			cry.pop();
		}
	}

	return 0;
}
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸥梨菌Honevid

栓Q

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值