查找地图中的最大值

新手上路,请多包涵

我一直在做一个基本程序来查找向量的最大值、最小值、中值、方差、众数等。一切都很顺利,直到我进入模式。

在我看来,我应该能够遍历向量,并且对于出现的每个数字,我都会在地图上增加一个键。找到具有最高值的键将是出现次数最多的键。与其他键比较会告诉我它是单个多重还是无模式答案。

这是给我带来很多麻烦的代码块。

 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

原文由 Sh0gun 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 573
2 个回答

您从未更改过代码中的 currentMax

 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;

找到模式的另一种方法是对向量进行排序并循环一次,跟踪值变化的索引。

原文由 YXD 发布,翻译遵循 CC BY-SA 3.0 许可协议

这可以在几行中完成,这是一个完整的工作片段:

 #include <iostream>
#include <algorithm>
#include <map>
int main() {
    std::map<char,int> x = { { 'a',1 },{ 'b',2 },{'c',0} };
    std::map<char,int>::iterator best
        = std::max_element(x.begin(),x.end(),[] (const std::pair<char,int>& a, const std::pair<char,int>& b)->bool{ return a.second < b.second; } );
    std::cout << best->first << " , " << best->second << "\n";
}

原文由 Janek_Kozicki 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题