我有這個類如下:(?心不是那奇)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));
}
}
感謝所有的幫助,我很感激!
可以顯示構造函數的代碼? – 2012-04-22 14:09:33
如果數據成員不是指向映射的指針,那麼如何用'new'分配映射? – juanchopanza 2012-04-22 14:10:07
'map'是對象的一部分,所以它會自動構建和銷燬。很高興看到調用函數的代碼。 – 2012-04-22 14:10:35