【华为机试之C++】合并表记录

这篇博客介绍了如何使用C++的std::map数据结构来处理键值对数据,通过创建一个名为Combiner的类,实现了对输入的键值对按索引合并并求和的功能。在输入数据验证和输出数据排序方面也做了相应的处理,确保了索引值不超过11111111,数值在1到100000之间,并且最终输出按索引升序排列。示例展示了不同输入情况下的正确输出结果,证明了代码的正确性和健壮性。
摘要由CSDN通过智能技术生成

描述

数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。

提示:
0 <= index <= 11111111
1 <= value <= 100000

输入描述:

先输入键值对的个数n(1 <= n <= 500)
接下来n行每行输入成对的index和value值,以空格隔开

输出描述:

输出合并后的键值对(多行)

示例1

输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4

示例2

输入:
3
0 1
0 2
8 9
输出:
0 3
8 9

思路

  1. 看到键值对,并且最后还要以升序的方式输出,第一反应就是使用std::map。std::map的第三个模板参数就是用于指定如何排序的,默认为less(key),即按键值升序排列。

代码

Combiner.h

#pragma once
#include <mutex>

class Combiner
{
public:
	static Combiner* getInstance();

public:
	void combine();

private:
	Combiner() = default;
	~Combiner() = default;

private:
	static Combiner* instance;
	static std::mutex iMutex;
};

Combiner.cpp

#include <iostream>
#include <map>
#include <algorithm>
#include "Combiner.h"

Combiner* Combiner::instance = nullptr;
std::mutex Combiner::iMutex;

Combiner* Combiner::getInstance()
{
	std::unique_lock<std::mutex> lock(iMutex);
	if (nullptr == instance) {
		instance = new Combiner();
	}

	return instance;
}

void Combiner::combine()
{
	/* input */
	uint32_t count = 0;
	std::cin >> count;

	uint32_t index = 0;
	uint32_t value = 0;

	std::map<uint32_t, uint32_t> mapTable; //按KEY升序
	//std::map<uint32_t, uint32_t, std::greater<uint32_t>> mapTable;//按KEY降序
	mapTable.clear();

	while (count) {
		std::cin >> index >> value;

		/* verify validity */
		if (index > 11111111) {
			std::cout << "An index greater than 11111111" << std::endl;
			continue;
		}

		if (value < 1 || value > 100000) {
			std::cout << "A value less than 1 or greater than 100000" << std::endl;
			continue;
		}

		/* combine */
		
		auto idx = mapTable.begin();
		for (; idx != mapTable.end(); idx++) {
			if (index == idx->first) {
				idx->second += value;
				break;
			}
		}

		if (idx == mapTable.end()) {
			mapTable[index] = value;
		}

		count--;
	}

	/* output */
	for (auto& ele:mapTable) {
		std::cout << ele.first << " " << ele.second << std::endl;
	}
}

main.cpp

#include "Combiner.h"

int main(int argc, char** argv)
{
	auto combiner = Combiner::getInstance();

	combiner->combine();

	return 0;
}

测试

测试环境

visual studio 2019

测试结果

输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
输入:
3
0 1
0 2
8 9
输出:
0 3
8 9
输入:
5
1 1
2 3
1 3
2 5
输出:
1 4
2 8
5 7
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值