可能重複:
Count the number of times each word occurs in a file字數節目++
嗨,
它以來我做了我的C++編程很長的時間。
這可能是一個相當愚蠢的問題。
我在這個網站上發現了幾個關於字數統計的程序。
但他們大多數都使用std::string
作爲他們的關鍵。
在我的情況下,我需要使用char*
作爲我的鑰匙。
但似乎因爲每個char*
有不同的地址值,重複的鍵正在插入我的地圖。
char str[] = "This This";
typedef std::map<char*, int> word_count_t;
typedef word_count_t::iterator word_count_iter_t;
int _tmain(int argc, _TCHAR* argv[])
{
char *token = strtok(str, " ");
word_count_t word_count;
word_count_iter_t itr = NULL;
while(token) {
++word_count[token];
token = strtok(NULL, " ");
}
for(itr = word_count.begin(); itr != word_count.end(); itr++) {
std::cout << "Key: " << itr->first << ", Value: " << itr->second << std::endl;
}
getchar();
}
我米獲得此程序的輸出是
鍵:這值:1
鍵:這值:1
我想輸出像
Key:This,Value:2
有人可以告訴我我在哪裏錯過了什麼?
謝謝。
地圖不能有重複的鍵,你應該使用multimap。 – 2011-05-26 08:33:55
@Als他不想重複鍵。 – 2011-05-26 08:36:32
@Nawaz除了他不計算文件中的單詞。 – 2011-05-26 08:38:23