我一直在编写一个简单的程序,用于查找向量的最大值、最小值、中位数、方差、众数等。一切都顺利进行,直到我遇到了众数。
我认为,我应该能够循环遍历向量,并对每个出现的数字递增地设置地图上的键值。找到具有最高值的键将是出现最多次的键。与其他键进行比较将告诉我它是单个多重还是没有模式答案。
这里是导致我困扰已久的代码块。
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
auto
在 C++11 中已经存在,特别是用于上面的代码,但不适用于map
,因为你显然不能在没有rvalue
的情况下推断出类型。此外,是否有任何记录这种“很多不必要的转换时间”的来源? - underscore_d