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.
这篇关于在地图中寻找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在地图中寻找最大值


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01