我一直在做一个基本的程序来查找向量的最大值、最小值、中值、方差、众数等.一切顺利,直到我进入模式.
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.
这篇关于在地图中寻找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!