C++利用键值对计算某一个数对应的最值及其索引位置

在这里插入图片描述

本文由CSDN点云侠原创,原文链接。如果你不是在点云侠的博客中看到该文章,那么此处便是不要脸的爬虫与GPT。

一、算法概述

  类似下图所示,计算第一列中1或2对应的最大值。
在这里插入图片描述

二、代码实现

1、计算最值

#include <map>
#include <vector>
#include <iostream>

int main() 
{
	// 示例数据
	std::vector<std::pair<int, int>> data = { {1, 100}, {1, 101}, {1, 102}, {2, 100}, {2, 101}, {2, 102} };
	// 使用std::map来存储每个键的最大值
	std::map<int, int> maxValues;
	// 迭代数据
	for (const auto& pair : data) 
	{
		// 如果这个键还没有在map中,或者当前值大于map中存储的值,更新它
		if (maxValues.find(pair.first) == maxValues.end() || pair.second > maxValues[pair.first]) 
		{
			maxValues[pair.first] = pair.second;
		}
	}
	// 输出结果
	for (const auto& maxPair : maxValues) 
	{
		std::cout << "Column1 value " << maxPair.first << " has a maximum Column2 value of " << maxPair.second << std::endl;
	}

	return 0;
}

2、计算最值及其索引

#include <map>
#include <vector>
#include <iostream>

int main() 
{
	// 示例数据,每个pair是{第一列的值, 第二列的值}
	std::vector<std::pair<int, int>> data = { {1, 100}, {1, 101}, {1, 102}, {2, 100}, {2, 101}, {2, 102} };
	// 使用std::map来存储每个键的最大值的索引
	std::map<int, int> maxIndices;
	// 使用std::map来存储每个键的当前最大值
	std::map<int, int> maxValues;
	// 迭代数据,i 是行数索引
	for (int i = 0; i < data.size(); ++i) 
	{
		const auto& pair = data[i];
		// 检查是否需要更新最大值和行数索引
		if (maxValues.find(pair.first) == maxValues.end() || pair.second > maxValues[pair.first]) 
		{
			maxValues[pair.first] = pair.second;
			maxIndices[pair.first] = i;  // 更新行数索引
		}
	}
	// 输出结果
	for (const auto& maxIndex : maxIndices) 
	{
		std::cout << "Column1 value " << maxIndex.first
			<< " has a maximum Column2 value in row " << maxIndex.second << std::endl;
	}

	return 0;
}

三、结果展示

Column1 value 1 has a maximum Column2 value of 102
Column1 value 2 has a maximum Column2 value of 102

Column1 value 1 has a maximum Column2 value in row 2
Column1 value 2 has a maximum Column2 value in row 5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

点云侠

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值