繁体   English   中英

计算每个单词在输入中出现的次数

[英]Count how many times each distinct word appears in input

我正在从Accelerated C ++进行练习:

编写一个程序,计算每个单词在其输入中出现的次数。

这是我的代码:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    // Ask for 
    // and read the input words
    std::cout << "Please input your words: " << std::endl;
    std::vector<std::string> word_input;
    std::string word;
    int count = 0;
    while (std::cin >> word)
    {
        word_input.push_back(word);
        ++count;
    }

    // Compare the input words 
    // and output the times of every word compared only with all the words

    /***** I think this loop is causing the problem ******/
    for (int i = 0; i != count; ++i)
    {
        int time = 0;
        for (int j = 0; j != count; ++j)
        {
            if (word_input[i] == word_input[j])
                ++time;
            else
                break;
        }

        std::cout << "The time of "
                    << word_input[i]
                    << " is: "
                    << time
                    << std::endl;
    }

    return 0;   
}

如果编译并运行该程序,您将看到:

Please input your words:

我输入如下:

good good is good
EOF

然后显示:

The time of good is: 2
The time of good is: 2
The time of is is: 0
The time of good is: 2

我的预期结果是:

The time of good is: 3
The time of is is: 1

我不想使用地图,因为我还没有学过。

是什么导致此意外行为,如何解决?

假设此时std :: vector是您唯一熟悉的容器,并且还没有达到std :: pair,我建议如下:

  • 您添加一个std::vector<int> word_count
  • std::cin while循环中,检查word_input是否存在当前单词。 如果不是,你push_back字和push_back在1 word_count 如果在word_input某个索引i处已经有当前单词的条目,则可以在此索引i处增加word_count 因此,您输入的每个不同单词仅在word_input出现一次 ,输入的次数在word_count进行管理。
  • 对于输出,并行执行word_inputword_count并输出每个单词的单词计数。

完成。

但是通过std::map所有这些变得更加简单和优雅。 继续阅读! :-)

只需删除else语句。

int main()
{
    // Ask for 
    // and read the input words
    std::cout << "Please input your words: "
              << std::endl;
    std::vector<std::string> word_input;
    std::string word;
    int count = 0;
    while (std::cin >> word)
        {
            word_input.push_back(word);
            ++count;
        }

    // Compare the input words 
    // and output the times of every word compared only with all the words
    for (int i = 0; i != count; ++i)
        {
            int time = 0;
            for (int j = 0; j != count; ++j)
                {
                    if (word_input[i] == word_input[j])
                        ++time;
                    // else          <========== You don't need this!
                    //    break;
                }

            std::cout << "The time of "
                 << word_input[i]
                 << " is: "
                 << time
                 << std::endl;
        }

    return 0;   
}

请注意,对于较大的输入,您的解决方案非常慢。 更好的主意是为您的“字典”使用hashtable(std :: map)或对该向量进行排序,而不是对不同的单词进行计数(以O(logN * N)运行,您的解决方案是O(N ^ 2))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM