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
相关推荐
墨染点香几秒前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
go54631584651 分钟前
基于分组规则的Excel数据分组优化系统设计与实现
人工智能·学习·生成对抗网络·数学建模·语音识别
茫茫人海一粒沙7 分钟前
vLLM 的“投机取巧”:Speculative Decoding 如何加速大语言模型推理
人工智能·语言模型·自然语言处理
诗酒当趁年华9 分钟前
【NLP实践】二、自训练数据实现中文文本分类并提供RestfulAPI服务
人工智能·自然语言处理·分类
枫叶丹420 分钟前
【Qt开发】信号与槽(二)-> 信号和槽的使用
开发语言·qt
静心问道39 分钟前
Idefics3:构建和更好地理解视觉-语言模型:洞察与未来方向
人工智能·多模态·ai技术应用
sheep888841 分钟前
AI与区块链Web3技术融合:重塑数字经济的未来格局
人工智能·区块链
奋进的孤狼1 小时前
【Spring AI】阿里云DashScope灵积模型
人工智能·spring·阿里云·ai·云计算
AIGC_北苏1 小时前
让UV管理一切!!!
linux·人工智能·uv
Vertira1 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python