【问题标题】:C++ Looking for the Element with the highest occurrence in an arrayC++ 寻找数组中出现次数最多的元素
【发布时间】:2013-05-01 00:11:57
【问题描述】:

我正在寻找一种优雅的方法来确定 C++ ptr 数组中哪个元素出现次数最多(模式)。

例如,在

{"pear", "apple", "orange", "apple"}

"apple" 元素是最常见的元素。

我之前的尝试都失败了 编辑:数组已经排序。

int getMode(int *students,int size)
{
    int mode;
    int count=0, 
    maxCount=0,
    preVal;

    preVal=students[0]; //preVall holds current mode number being compared
    count=1;
    for(int i =0; i<size; i++) //Check each number in the array
    {
        if(students[i]==preVal) //checks if current mode is seen again
        {
            count++; //The amount of times current mode number has been seen.
            if(maxCount<count)  //if the amount of times mode has been seen is more than maxcount
            {
                maxCount=count; //the larger it mode that has been seen is now the maxCount
                mode=students[i]; //The current array item will become the mode
            }else{
                preVal = students[i];
                count = 1;
            }

        }

    }

    return mode; 
}

【问题讨论】:

  • 对数组进行排序是一种选择吗?治疗会更简单/快速。
  • 哦,忘了说已经排序了。
  • 嗯...所以你的数组看起来像['apple', 'apple', 'orange', 'pear'] ?
  • 一点也不,它是一个动态分配的数组,用户在其中输入值。
  • 你告诉我“它已经排序了”。那它是如何排序的呢?但是你应该看看 Arne Mertz 的回答,他(她)的回答都说了。

标签: c++ arrays algorithm pointers mode


【解决方案1】:

这个问题有几种可能的解决方案,但首先是一些建议: 不要使用 C 风格的数组。使用std::array 用于固定(编译时)大小的数组或std::vector 用于堆上的数组(或C++14 的std::dynarray,如果数组大小在运行时确定但在创建后不更改)。这些容器为您进行内存管理,您无需单独传递数组大小。除了使用容器,更喜欢使用&lt;algorithm&gt; 中的算法。如果您不了解容器和算法,请花一些时间熟悉它们,时间很快就会得到回报。

所以,这里有一些解决方案草图:

  1. 对数组进行排序,然后计算连续值的出现次数。这比跟踪您已经计算过哪些值以及未计算过的值要容易得多。您基本上只需要两个值计数对:一个用于您当前计数的值,一个用于迄今为止的最大计数。您只需要第五个变量:容器的迭代器。

  2. 如果您无法对数组进行排序或需要跟踪所有个计数,请使用映射将值映射到它们在数组中出现的次数。如果你熟悉std::map,那很简单。最后,搜索最大计数,即最大map值:

    for (auto i: students) countMap[i]++;
    auto pos = std::max_element(begin(countMap), end(countMap), 
      [](auto lhs, auto rhs){ return lhs.second < rhs.second }); //! see below
    auto maxCount = pos->second;
    

注意:这使用基于 C++11 的范围和 C++14 多态 Lambda。这里所做的事情应该很明显,因此可以针对您的编译器提供的 C++11/C++14 支持进行调整。

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 2013-10-13
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2019-04-29
    • 2020-04-29
    相关资源
    最近更新 更多