C ++帮助查找地图中的最大值 [英] C++ Help finding the max value in a map
问题描述
所以我一直在寻找,尝试了许多不同的东西,在这一点上,我的头脑已经几乎融化,我不能直视。我一直在做一个基本的程序,以找到一个向量的最大值,最小值,中值,方差,模式等。一切都进行得很顺利,直到我进入模式。我甚至不能开始我想要的方式。
So I've been searching around and have tried many different things and at this point my mind has pretty much melted and I can't think straight. 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. I can't even get started the way I want to.
我看到它的方式,我应该能够循环通过向量,并为每个发生的数字我在地图上增加一个键。找到具有最高价值的密钥将是发生最多的密钥。与其他键比较会告诉我,如果它是一个单倍或没有模式答案。
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 occured the most. Comparing to other keys would tell me if it's a single multiple or no mode answer.
Unfortuneatley我遇到麻烦了,因为我没有经验的地图,并已经运行各种兼容性和语法错误。我知道我现在没有什么意义,但它在哪里我碰撞了。这里的代码块已经导致我这么多的麻烦。
Unfortuneatley I've run into trouble right off the bat with this as I have no experince with maps and have been running into all kinds of compatibility and syntax errors. I know what I have now doesn't make sense but it sort of where I've crashed into. 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
您可以提供任何帮助将是巨大的赞赏。先谢谢你。
Any help you guys can offer would be GREATLY appreicated. Thank you in advance.
推荐答案
您从未在代码中更改 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.
这篇关于C ++帮助查找地图中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!