2011-05-26 24 views
0

可能重複:
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

有人可以告訴我我在哪裏錯過了什麼?

謝謝。

+0

地圖不能有重複的鍵,你應該使用multimap。 – 2011-05-26 08:33:55

+0

@Als他不想重複鍵。 – 2011-05-26 08:36:32

+0

@Nawaz除了他不計算文件中的單詞。 – 2011-05-26 08:38:23

回答

2

你想要一個std::map<std::string, int> - 你的地圖char*將比較指針而不是它們指向的字符串。

1

std::map默認使用operator <進行比較的密鑰類型。 operator <char *比較指針地址,而不是字符串的字符。

你想用std::map<std::string, int>來替代,因爲operator <std::string沒有詞法字符串比較。

1

你必須使自己的比較類const char *

struct StrCmp { 
    static bool operator() (const char *a, const char *b) { 
     return strcmp(a, b)<0; 
    } 
}; 

然後你可以使用地圖:

所有的
typedef std::map<char const *, int, StrCmp> word_count_t; 
0

首先,你應該使用一些HashMap的實現。 std :: map是一個TreeMap,在計算巨大文本中的單詞時會更慢。這是由於這樣一個事實,即文本中的大量詞語將被映射到適量的不同單詞。即使你需要對輸出進行排序,之後對散列圖進行排序可能會更好,因爲插入到樹中將排序爲#發生*日誌#字,同時排序它們將是O(#words * log #words)

因此,大多數散列表實現(我個人通常使用google :: dense_hash_map或google :: sparse_hash_map)可以處理char *而無需編寫散列函數(它們使用stl散列函數)。所以它基本上就是爲你插播&。

0

鍵是不同的,因爲它們是char*,也就是指向內存中不同位置的指針。如果您使用了std::map<std::string, int>並且您做了++word_count[std::string(token)],您將獲得預期的輸出。