查找模式C++

Finding the Mode C++

本文关键字:C++ 模式 查找      更新时间:2023-10-16

如何编辑此函数以查找多种模式?现在,如果有多个,它将显示最小的。

输入 5 5 2 2 产出5 2

它实际上做了什么

输入 5 5 1 1 产出 1

void calculateMode(int array[], int big)
{
int counter = 1;
int max = 0;
int mode = array[0];
for (int pass = 0; pass < big - 1; pass++)
{
if ( array[pass] == array[pass+1] )
{
counter++;
if ( counter > max )
{
max = counter;
mode = array[pass];
}
} else
counter = 1; // reset counter.
}
cout << "The mode is: " << mode << endl;
}

什么都有帮助!

我也喜欢 stdlib 选项,因为其中一个评论引用了。但是,我试图解决这个问题,而不是像你一样使用它(作为练习)。我要求将常量数组作为函数参数,所以我无法对其进行排序(既不能删除常量,也不能将其复制到新的非常量数组中)。此外,如果有多个模式或没有元素,我必须返回零

最后,A想出了类似以下内容的东西。希望它可能会有所帮助。

#include <iostream>
#include <stdexcept>
template <typename T> T mode(const T *values, size_t length) {
// check if it has zero length
if (!length)
return 0;
if (!values)
throw std::invalid_argument{"Invalid input array"};
int count{}, maxOccurrences{};
int multipleModes{};
T mode{};
// check every element unless the mode's occurrences are greater than the
// remaining list
for (int k{}; k < length && maxOccurrences <= (length - k); ++k) {
// reset the count for every individual element
count = 0;
// count the number of occurrences
for (int i{}; i < length; ++i) {
if (values[k] == values[i])
count++;
}
if (count > maxOccurrences && mode != values[k]) {
mode = values[k];
maxOccurrences = count;
multipleModes = 0;
/*std::cout << "Count:" << count << " - MaxOccur:" << maxOccurrences
<< " - Mode:" << mode << std::endl;*/
}
if (count == maxOccurrences && mode != values[k]) {
// if the array has multiple modes
multipleModes = 1;
}
}
if (multipleModes == 1)
return 0;
else
return mode;
}

感谢您的关注!

你可以尝试添加这个

else if (counter==max){
mode += array[pass]
}

无法在我自己的系统上测试它。 看看是否有任何帮助。