计算每个不同词在其输入C ++中出现的次数 [英] Count how many times each distinct word appears in its input C++

查看:113
本文介绍了计算每个不同词在其输入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 ++中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆