2010-07-21 29 views
0

這裏是代碼地圖操作(找到最occurence元素)

#include <iostream> 
#include <map> 
using namespace std; 
int main(){ 
map<int ,int>a; 
    map<int,int>::iterator it; 
    int b[]={2,4,3,5,2,6,6,3,6,4}; 
    for (int i=0;i<(sizeof(b)/sizeof(b[0]));i++){ 
     ++a[b[i]]; 
    } 
    // for (it=a.begin();it!=a.end();it++){ 
     // cout<<(*it).first<<" =>"<<(*it).second<<"\n"; 
    //} 
    int max=a.begin()->second; 
    for (it=a.begin();it!=a.end();it++){ 
     if ((*it).second>max){ 
      max=(*it).second; 
     } 
    } 
    for (it!=a.begin();it!=a.end();it++){ 
     if ((*it).second==max){ 
      cout<<(*it).first<<"\n"; 
     } 
    } 




     return 0; 
} 

我試圖根據每個鍵的occurence數以下我希望它打印的最經常發生在這種情況下,6,但卻元素不顯示我導致什麼錯誤?

+1

一個提示是不要在一個函數中重用變量用於不同的目的。那會早早發現這個問題。如果類型名稱太大,會發現它阻礙了可讀性,請使用'typedef'。 'typedef map :: iterator MapIt;爲(MapIt it = ...)' – Stephen 2010-07-21 16:49:47

回答

4

您的第二個循環中有錯字。這:

for (it!=a.begin();it!=a.end();it++){ 

應該是這樣的:

for (it=a.begin();it!=a.end();it++){ 

順便說一句,(*it).first可以更地道寫成it->first。箭頭運算符(->)是解引用(*)和成員訪問(.)運算符的組合。

3

您的第二個循環應該以it=a.begin()開頭,而不是it!=a.begin()。但是,爲什麼不捕獲在捕獲max時最頻繁發生的數字,並且完全擺脫第二個循環?

1

鑑於您在做什麼,您可能會考慮使用Boost bimap而不是普通地圖。有了它,您的代碼會制定出這樣的事:

#include <boost/bimap.hpp> 
#include <boost/bimap/list_of.hpp> 
#include <iostream> 

int main() {  
    int b[]={2,4,3,5,2,6,6,3,6,4}; 

    boost::bimap<int, boost::bimaps::list_of<unsigned> > a; 

    for (int i=0; i<elements(b); i++) 
     ++a.left[b[i]]; 

    std::cout << a.right.rbegin()->second; 
} 

醜陋這裏的一位是要看是什麼將是值類型正常初始化默認構造函數,這int不,所以我們必須從list_of<unsigned>改變list_of<uint_proxy>,與uint_proxy定義是這樣的:

class uint_proxy { 
    unsigned value; 
public: 
    uint_proxy() : value(0) {} 
    uint_proxy& operator++() { ++value; return *this; } 
    unsigned operator++(int) { return value++; } 
    operator unsigned() const { return value; } 
}; 

在這種情況下,代理型增加了更多的位長度比我們想,但對主流代碼通過比較仍然非常簡單,並且通常會相當大更高效 - 特別是,它可以避免線性掃描找到計數最高的密鑰。對於可能不相關的測試用例而言,大量的數據可能更爲重要。