C ++中的字计数程序 [英] Word count program in C++
问题描述
可能重复:
计算文件中每个字出现的次数
您好,
自从我做C ++编程以来已经很久了。
这可能是一个很蠢的问题。 br>
我在这个网站上找到了几个关于字数的程序。
但是大多数程序使用 std :: string
键。
在我的例子中,我需要使用 char *
作为我的键。
但是似乎每个 char *
有不同的地址值,重复的键已插入到我的地图中。
Hi,
Its been a long time since I did my C++ programming.
This could be quite a dumb question.
I have found several programs on word count in this site.
But most of them are using std::string
as their keys.
In my case, I needed to use char*
as my key.
But it seems since each char*
has different address values, the duplicate keys are getting inserted in my map.
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: 1
Key: This, Value: 1
我想输出像
键:This,Value:2
Key: This, Value: 2
有人可以告诉我我在哪里错过什么?
Can somebody tell me where did I miss what?
谢谢。
推荐答案
你想要一个 std :: map< std :: string,int>
code> char * 将比较指针而不是它们指向的字符串。
You want a std::map<std::string, int>
- your map of char*
will be comparing pointers not the strings they point to.
这篇关于C ++中的字计数程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!