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
相关推荐
深耕AI16 分钟前
【MFC文档与视图结构:数据“仓库”与“橱窗”的梦幻联动 + 初始化“黑箱”大揭秘!】
c++·mfc
会写代码的饭桶20 分钟前
通俗理解 LSTM 的三门机制:从剧情记忆到科学原理
人工智能·rnn·lstm·transformer
算家计算26 分钟前
ComfyUI-MultiTalk本地部署教程:创新L-RoPE机制破解多音频流绑定难题,定义多人对话视频生成新SOTA!
人工智能·开源
Stestack27 分钟前
人工智能常见分类
人工智能·分类·数据挖掘
量子位29 分钟前
18岁女孩做养老机器人,上线2天卖爆了
人工智能·llm
上位机付工30 分钟前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
小林学习编程31 分钟前
2025年最新AI大模型原理和应用面试题
人工智能·ai·面试
数据分析能量站34 分钟前
大模型为什么会有幻觉?-Why Language Models Hallucinate
人工智能
励志不掉头发的内向程序员39 分钟前
STL库——二叉搜索树
开发语言·c++·学习
小白狮ww1 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习