2012-04-22 28 views
-2

我有這個類如下:(?心不是那奇)C++地圖和性能

class nLetterFrequency 
{ 
private: 
    map<string, int> frequencyTable; 

    void insert(const string& letterPerm); 
    void parseFile(int n);      //calls insert() 

public: 

    nLetterFrequency(int n);     //calls parseFile() 
    ~nLetterFrequency(); 
}; 

顯然沒有什麼錯我的代碼,事實證明,它只是需要2到3分鐘就完成。這對我來說似乎很詭異,因爲我首先用Java編寫了這個實現,並在幾秒鐘內完成。兩種語言之間的表現如何變得如此激烈?這是由於地圖類在C++和Java中實現的差異所致?在Java中,我使用了一個TreeMap,我也使用了一個HashMap,但切換到了TreeMap,因爲我想對我的地圖進行排序。這裏是parseDictionary函數的代碼,並插入函數。構造函數調用parseDictionary()就是這樣。

void nLetterFrequency::parseDictionary(int n) 
{ 
    ifstream infile("3dictionary.txt");  //length of words >= 3     


    while(!infile.eof())     //while we are not at the end of the file 
    { 
     string word; 

     getline(infile, word);   

     if(word.length() < n) 
     { 
     printf("Error: check the dictionary file since word.length() < n\n"); 
      exit(0); //quit the program 
     } 

     for(int i = 0; i < word.length() - n + 1; i++) 
     { 
      string perm(""); 
      for(int j = 0; j < n; j++) 
      { 
       perm += word[i+j]; 
      } 

      insert(perm); 
     } 

    } 

    infile.close(); 
} 


void nLetterFrequency::insert(const string& letterPerm) 
{ 
    if(frequencyTable.count(letterPerm))       //letterPerm is already in frequencyTable 
    { 
     frequencyTable.find(letterPerm)->second++;    //increment the current frequency of entry letterPerm 
    } 
    else                //insert the new permutation into frequencyTable 
    { 
     frequencyTable.insert(pair<string, int>(letterPerm, 1)); 
    } 
} 

感謝所有的幫助,我很感激!

+2

可以顯示構造函數的代碼? – 2012-04-22 14:09:33

+2

如果數據成員不是指向映射的指針,那麼如何用'new'分配映射? – juanchopanza 2012-04-22 14:10:07

+2

'map'是對象的一部分,所以它會自動構建和銷燬。很高興看到調用函數的代碼。 – 2012-04-22 14:10:35

回答

0

似乎不太可能在300,000行至BARF,但你需要做算術。 30萬行中有多少個「字符串」?假設你可能意思是'單詞',也許這就是大約500萬字。也許每個單詞都是8個字符。瘋狂猜測,這可能是每個映射節點32個字節。總計大約160 MB。不是很多。

什麼是構造函數參數「N」的呢?你是否說在插入字符串之前它失敗了?

+3

請使用'comment'來問領導的問題和'answer'實際回答他們(-' – 2012-04-22 14:15:46

+1

有2個問題 - 一個是「它有與內存分配做」我的回答是「可能不會」(與工作顯示)雖然,一般的觀點。 – dave 2012-04-22 14:18:23

0

所有內存分配內部地圖處理,所以恕我直言,你不需要爲它分配兩次,其他時間(一個時間你constructur(隱含)內) - 你的構造體內部。除非地圖的生命週期應該大於nLetterFrequency對象。