vector 自定义排序规则,string 类型分割实现

vector 自定义排序规则,string 类型分割实现

首先看一道算法题目:Olympic Game
我们需要根据各个国家的所获得的奖牌数,进行排序,排序规则如下

  • 首先按照金牌数目排序,所获得的金牌数量越多,排序越靠前
  • 当金牌数量相等时,按照获得的银牌的数量进行排序
  • 当金牌和银牌的数量都相等时,按照铜牌的数量进行排序
  • 当三种奖牌的数量都相等时,按照国家名称的字典顺序进行排序

输入规则:

  1. 第一行输入一个整数N(0<N<21),代表国家数量
  2. 接下来输入N行,每行包含一个字符串Namei表示每个国家的名称,和三个整数G,S,B分别表示:gold medal(金牌),silver medal(银牌),bronze medal(铜牌)的数量,以空格隔开。如(China 51 20 21)。

输出
输出奖牌榜的依次顺序,指输出国家的名称,各占一行

输入样例
5
China 32 28 34
England 12 34 22
France 23 33 2
Japan 12 34 25
Rusia 23 43 0

输出样例
China
Rusia
France
Japan
England

解题思想

  1. 首先使用 getline() 函数接收输入的数据
  2. 对接收的数据 根据空格进行拆分,由于C++ 没有内置例如split() 这样的字符串拆分函数,因此只能自己实现。主要通过使用find() 函数和 substr() 函数来实现字符串的拆分。
  3. 将拆分的字符串保存在 vector<pair<string,vector>>结构体中
  4. 重写sort() 函数的排序规则 MyCom

具体代码如下:

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

//重写sort()排序规则
class MyCom
{
public:
//使用运算符重载,对()进行重写
	bool operator()(const pair<string, vector<string>> &v1, const pair<string, vector<string>> &v2) {
		if (v1.second[0] != v2.second[0]) {
			return v1.second[0] > v2.second[0];
		}
		else if (v1.second[0] == v2.second[0] && v1.second[1] != v2.second[1]) {
			return v1.second[1] > v2.second[1];
		}
		else if (v1.second[0] == v2.second[0] && v1.second[1] == v2.second[1] && v1.second[2] == v2.second[2]) {
			return v1.second[2] > v2.second[2];
		}
		else {
			return v1.first > v2.first;
		}
	}
};

int main()
{
	cout << "请输入数量" << endl;
	int num;
	cin >> num;
	vector<pair<string, vector<string>>> v;
	string str;
	for (int i = 0; i <= num; i++) {
		getline(cin, str);
		//if 语句是为了 避免接收 第一行数据,这一点一直没找到好的方法,暂时只能使用这种比较笨的方法
		if (i == 0) {
			continue;
		}
		int pos = -1;
		int start = 0;
		vector<string> v_temp;
		string temp;
		//while 函数对字符串进行拆分
		while (true) {
			pos = str.find(" ",start);
			if (pos == -1) {  
				v_temp.push_back(str.substr(start));
				break;
			}
			if (start == 0) {
				temp = str.substr(start, pos - start);
			}
			else {
				v_temp.push_back(str.substr(start, pos - start));
			}
			start = pos + 1;
		}
		v.push_back(make_pair(temp, v_temp));
	}
	sort(v.begin(), v.end(), MyCom());
	cout << "排序后结果" << endl;
    //打印输出
	for (vector<pair<string, vector<string>>>::iterator it = v.begin(); it != v.end(); it++) {
		cout << it->first  << endl;
	}

	system("pause");
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值