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
相关推荐
Bruce_Liuxiaowei2 分钟前
当AI以可验证的方式攻克数学难题——它如何重写了“科研“的成本与门槛
人工智能·智能体
C++、Java和Python的菜鸟3 分钟前
第10章 后端Web进阶(Maven高级)
开发语言·python
deepseek237 分钟前
MiniMax H3 全模态模型拆解:2K 视频成本被腰斩背后,H3-VAE 和 In-context Regeneration 做了什么
人工智能·多模态·视频生成
智道天成9 分钟前
杭州智道天成信息科技有限公司:助力浙江企业合规高效落地
大数据·人工智能·科技
董员外18 分钟前
RAG 系统进化论(五):Corrective RAG 与 Self-RAG,让系统发现并纠正错误
人工智能·后端·设计模式
MistyStar20 分钟前
Fast 模式为什么更快也更贵:从 Prefill/Decode 到 Batch 经济学
人工智能
小罗水33 分钟前
第 20 章 高级 RAG 技术与检索优化
人工智能·python·机器学习
神罚天下ET39 分钟前
.NET 新增功能系列文章——C# 中的新增功能
开发语言·c#·.net
所愿ღ40 分钟前
SSM框架-Spring3
java·开发语言·笔记·spring
维克兜率天42 分钟前
【维克】正则化回归:从Lasso到Ridge:防止过拟合的数学魔法
人工智能·数据挖掘·回归