【发布时间】:2011-05-26 08:29:13
【问题描述】:
嗨,
我已经很久没有进行 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
我想要像这样的输出
键:这个,值:2
谁能告诉我我错过了什么?
谢谢。
【问题讨论】:
-
一个 Map 不能有重复的键,你应该使用 multimap。
-
@Als 他不想要重复的键。
-
@Nawaz 除了他没有计算文件中的单词。
标签: c++