我正在尋找一種確定哪個元素在C++ ptr數組中具有最高出現(模式)的優雅方法。C++尋找在數組中發生率最高的元素
例如,在
{"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;
}
排序數組是一個選項?治療將更加簡單/快速。 – MisterJ 2013-05-07 06:18:03
哦,忘了提及它已經排序。 – 2013-05-07 06:19:34
哼...所以你的數組看起來像'['蘋果','蘋果','橙','梨']'? – MisterJ 2013-05-07 06:20:56