Finding the max value in a map(在地图中寻找最大值)
问题描述
我一直在做一个基本的程序来查找向量的最大值、最小值、中值、方差、众数等.一切顺利,直到我进入模式.
I've been doing a basic program to find the max, min, median, variance, mode etc. of a vector. Everything went fine until I got to the mode.
在我看来,我应该能够遍历向量,并且对于出现的每个数字,我都会在地图上增加一个键.找到具有最高值的键将是出现次数最多的键.与其他键相比,我会知道它是单多还是无模式应答.
The way I see it, I should be able to loop through the vector, and for each number that occurs I increment a key on the map. Finding the key with the highest value would then be the one that occurred the most. Comparing to other keys would tell me if it's a single multiple or no mode answer.
这是给我带来很多麻烦的代码块.
Here's the chunk of code that's been causing me so much trouble.
map<int,unsigned> frequencyCount;
// This is my attempt to increment the values
// of the map everytime one of the same numebers
for(size_t i = 0; i < v.size(); ++i)
frequencyCount[v[i]]++;
unsigned currentMax = 0;
unsigned checked = 0;
unsigned maax = 0;
for(auto it = frequencyCount.cbegin(); it != frequencyCount.cend(); ++it )
//checked = it->second;
if (it ->second > currentMax)
{
maax = it->first;
}
//if(it ->second > currentMax){
//v = it->first
cout << " The highest value within the map is: " << maax << endl;
可以在这里看到整个程序.http://pastebin.com/MzPENmHp
The entire program can be seen here. http://pastebin.com/MzPENmHp
推荐答案
您从未更改代码中的 currentMax
.
You never changed currentMax
in your code.
map<int,unsigned> frequencyCount;
for(size_t i = 0; i < v.size(); ++i)
frequencyCount[v[i]]++;
unsigned currentMax = 0;
unsigned arg_max = 0;
for(auto it = frequencyCount.cbegin(); it != frequencyCount.cend(); ++it ) }
if (it ->second > currentMax) {
arg_max = it->first;
currentMax = it->second;
}
}
cout << "Value " << arg_max << " occurs " << currentMax << " times " << endl;
另一种找到模式的方法是对向量进行排序并循环遍历一次,跟踪值发生变化的索引.
Another way to find the mode is to sort the vector and loop through it once, keeping track of the indices where the values change.
这篇关于在地图中寻找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在地图中寻找最大值
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01