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
相关推荐
历程里程碑几秒前
MySQL数据类型全解析 + 代码实操讲解
大数据·开发语言·数据库·sql·mysql·elasticsearch·搜索引擎
ZC跨境爬虫1 分钟前
Python Django开发者转向微信小程序:从架构理解到第一行代码的完整准备指南
开发语言·python·ui·微信小程序·django
ACP广源盛139246256732 分钟前
一芯搞定多屏高清@ACP#GSV1221 DP 1.4 MST 转 HDMI 1.4 高集成转换芯片
网络·人工智能·嵌入式硬件·计算机外设·电脑
沐知全栈开发3 分钟前
Eclipse 首选项(Preferences)详解
开发语言
MClink5 分钟前
Trae 自定义模型接入指南:把 DeepSeek、GLM、Qwen 装进你的 AI 编程助手
人工智能·大模型
测试员周周9 分钟前
【AI测试系统】第6篇:需求扔进去,3 分钟出测试用例?AI测试系统的 RAG 知识增强实战
人工智能·python·功能测试·测试工具·测试用例
Godspeed Zhao11 分钟前
具身智能中的传感器技术40.2——事件相机0.2
人工智能·科技·数码相机·机器学习·事件相机
庞轩px12 分钟前
大模型为什么会有“幻觉”——从训练方式到推理局限
人工智能·prompt·rag·大模型幻觉·engineering·训练方式
Rust研习社12 分钟前
Weak 弱引用:如何用 Weak 打破 Rc 与 Arc 的循环引用
开发语言·后端·rust
iCxhust13 分钟前
在 emu8086 中可以直接编译运行的完整汇编程序,演示数组的定义、遍历、求和、求最大值。
开发语言·前端·javascript·汇编·单片机·嵌入式硬件·算法