【发布时间】: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