2013-05-07 100 views
0

我正在尋找一種確定哪個元素在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; 
} 
+0

排序數組是一個選項?治療將更加簡單/快速。 – MisterJ 2013-05-07 06:18:03

+0

哦,忘了提及它已經排序。 – 2013-05-07 06:19:34

+0

哼...所以你的數組看起來像'['蘋果','蘋果','橙','梨']'? – MisterJ 2013-05-07 06:20:56

回答

4

有該問題的幾種可能的解決方案,但首先一些建議: 不要使用C風格的數組。對於固定(編譯時)大小的數組,使用std::array;對於堆上的數組,則使用std::array;如果數組大小在運行時確定,但在創建後不更改,則使用C++ 14的std::dynarray。這些容器爲您執行內存管理,並且不需要單獨傳遞數組大小。除了使用容器之外,更喜歡使用<algorithm>中適用的算法。如果你不知道容器和算法,花一些時間去熟悉它們,這段時間很快就會得到回報。

所以,這裏有一些解決方案的草圖:

  1. 排序數組,然後計算連續值的ocurrences。跟蹤哪些數值已經計算,哪些不計算,要容易得多。您基本上只需要兩個值計數對:一個用於您當前正在計數的值,一個用於至今爲止的最大值。你只需要第五個變量:容器的迭代器。

  2. 如果您無法對數組進行排序或需要跟蹤所有計數,請使用映射將值映射到數組中的出現次數。如果您熟悉std::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支持進行調整。