C ++中Ints的向量的寻找模式 [英] Finding Mode of Vector of Ints in C++
问题描述
所以我试图做一个基本的程序来学习C ++的基础知识,我从0到100生成100个随机数,并将它们存储在一个向量中,然后显示sum,mean,median,mode ,高和低的向量。我有一切做,除了模式,这是我被困住的地方。这是我到目前为止的代码。
So I'm trying to make a basic program to learn the basics of C++, I'm generating 100 random numbers from 0 to 100 and storing them in a vector, I am then displaying the sum, mean, median, mode, high and low of the vector. I have everything else done except the mode which is where I get stuck. Here is the code I have so far.
int modeFunction()
{
numMode = 0;
count = 0;
for (int n = 0; n < 100; n++)
{
for (int y = 0; y < 100; y++)
{
if (numVector.at(y) == numVector.at(n))
{
numMode = numVector.at(y);
count++;
}
}
}
return numMode;
}
之后,我被困住,因为在我心中应该工作, t。
After that I get stuck because in my mind that should work but it doesn't. It just out puts the last number, usually 100. Any help would be much appreciated.
推荐答案
因为所有的值都在0之间和100,可以使用直方图有效地找到该模式:
since all the values are between 0 and 100, you can find the mode efficiently with a histogram:
std::vector<int> histogram(101,0);
for( int i=0; i<100; ++i )
++histogram[ numVector[i] ];
return std::max_element( histogram.begin(), histogram.end() ) - histogram.begin();
这篇关于C ++中Ints的向量的寻找模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!