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

目录

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

一、算法概述

  类似下图所示,计算第一列中1或2对应的最大值。

二、代码实现

1、计算最值

cpp 复制代码
#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、计算最值及其索引

cpp 复制代码
#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;
}

三、结果展示

cpp 复制代码
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
相关推荐
yychen_java几秒前
第二篇:从世界模型到 Physical AI——一套可落地的工业智能体架构
人工智能·架构
matlab代码4 分钟前
基于matlab多尺度形态学提取眼前节组织【源码73期】
图像处理·人工智能·计算机视觉
IT_陈寒7 分钟前
Redis的Set操作居然能把我的服务整挂了?
前端·人工智能·后端
老王爱玩车10 分钟前
深入理解指针2
c语言·开发语言·学习
Mininglamp_271811 分钟前
MCP和A2A之后,机器人网络里还缺一层开放通信协议
人工智能·agent·多智能体·具身智能
quantdash_cc13 分钟前
股票历史数据为什么比实时行情更重要?回测结果失真的根源可能就在 K 线数据
开发语言·python·数据分析·量化交易·股票数据·quantdash
angered23 分钟前
「AI 应用 / AI Agent」行业日报 · 2026-09-08
人工智能·ai编程
光电的一只菜鸡25 分钟前
为什么调整LSC会对AF产生影响
android·开发语言·kotlin
zhangjw3428 分钟前
第47篇:Java综合实战:电商秒杀系统(高并发场景)
java·开发语言