计算每个不同词在其输入C ++中出现的次数

编程入门 行业动态 更新时间:2024-10-14 20:26:48
本文介绍了计算每个不同词在其输入C ++中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <iostream> #include <string> #include <sstream> #include <map> int main() { std::string input; std::cout << "Enter input: "; std::getline(std::cin, input); std::map<std::string, int> m; std::map<std::string, int>::iterator it; std::istringstream iss(input); std::string words; do { iss >> words; it = m.find(words); if(it != m.end()) { m.insert(it, std::pair<std::string, int>(words, m[words] + 1)); } else { m.insert(std::pair<std::string, int>(words, 1)); } }while(iss); for(std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) { std::cout << it->first << " - " << it->second << std::endl; } return 0; }

问题是每个单词都打印1次,即使它出现两次。可能是什么问题?

The problem is that it prints 1 for every word, even if it appears twice. What could be the problem? I'm not sure if my test for an iterator not to be empty is correct.

推荐答案

因为 map 使用默认构造函数自动构造一个项,当你访问一个还不存在的键时,你可以简单地说:

Because map automatically constructs an item with the default constructor, when you access a key that doesn't exist yet, you can simply say:

while (iss >> words) { ++m[words]; }

新项目的默认值将为0(请参阅此问题)。

The default value of new items will be 0 (see this question).

您之前的地图逻辑很好除非你的情况反转了;它应该是 if(it == m.end())而不是!= ,因为 find()在元素未时返回 end()正如GWW在他的答案中指出的, insert 在项目已经在地图中时是没有效果的,这是你使用它的唯一时间。

Your previous map logic was fine except that you had the condition reversed; it should have been if (it == m.end()) instead of !=, since find() returns end() when the element is not found. As GWW points out in his answer, insert has no effect when the item is already in the map, which is the only time you were using it.

此外,你的循环没有正确处理输入;您需要在读取值之后检查流的状态是否无效,之后之前使用它(因为如果流在结束时该值是无用的) 。处理输入的惯用方法是使用 while(is>> value)构造;如果你想自己做,那么这是等价的:

Also, your loop was not handling input properly; you need to check if the state of the stream is invalid after reading in the value, but before using it (since the value is garbage if the stream was at its end). The idiomatic way to handle input is with the while (is >> value) construct; if you want to do it yourself then this is equivalent:

while (true) { iss >> words; if (!iss) { break; } // Process words... }

$ b b

最后,当你的变量words一次只包含一个单词时,有点误导; - )

Finally, it's a little misleading to name your variable "words" when it will only contain one word at a time ;-)

更多推荐

计算每个不同词在其输入C ++中出现的次数

本文发布于:2023-11-30 17:28:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:次数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!