问题描述
所以我一直在寻找,尝试了许多不同的东西,在这一点上,我的心灵已经融化了很多,我不能直视。我一直在做一个基本的程序,找到一个向量的最大,最小,中位数,方差,模式等。一切顺利,直到我进入模式。我甚至不能开始我想要的方式。
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;
整个程序可以在这里看到。
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 ++帮助在地图中找到最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!