【问题标题】:Most efficient structure to count unique words in a file [C++]计算文件中唯一单词的最有效结构 [C++]
【发布时间】:2013-03-13 14:44:08
【问题描述】:

我正在尝试创建一个程序来计算文件中单词的唯一出现次数,然后按字母顺序显示它们的计数。

关键是要尽可能以最快和最有效的方式做到这一点。

请记住,我正在使用 C++ 编写代码,但我并不反对纯理论答案。

有什么建议吗?

【问题讨论】:

  • std::map<std::string, int> word_count
  • 到目前为止你做了什么?我真的找不到比某种地图“更好”的解决方案,并从文件中读取每个单词并在地图中累积匹配位置。

标签: c++ performance sorting data-structures word-count


【解决方案1】:

这是一个使用 cin 的示例。

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    string word;
    std::map<std::string, int> word_count;

    while (std::getline(cin, word, ' ')) {
        word_count[word]++;
    }

    typedef std::map<std::string, int>::iterator iter;
    iter end = word_count.end();
    for(iter it = word_count.begin(); it != end; ++it) {
        cout << it->first << ", count= " << it->second << endl;
    }

    return 0;
}

【讨论】:

  • 如果密钥不存在,operator[]() 将插入一个默认初始化值(在本例中为 0),因此没有理由事先使用 find() 进行检查。另外,unordered_map 可能会更快。
  • 已更新。同意哈希映射如果可用会更好。
  • 你需要在最后迭代它们,而不是像你正在经历的那样。
【解决方案2】:

我认为你应该使用 2 个 std::set 和一些“1 次使用的单词”和“禁止的单词:使用两次或更多次”。

所以你处理了一个词:cur_word。如果forbidden_​​words 包含它,则忽略它,否则检查allowed_words 是否包含,将其删除并添加到forbidden_​​words,否则只需添加它do allowed_words。

【讨论】:

    【解决方案3】:

    std::unordered_set 可能比std::set 快(尤其是在文件很大的情况下)。

    但这不太可能有太大的不同——除非你写得非常糟糕,否则这项工作将受到大量 I/O 限制,因此你的大部分工作都应该放在加速 I/O 上。

    如何从那里继续可能取决于目标操作系统。对于 Linux,快速文件读取主要等同于mmap。对于 Windows,您通常希望避免使用内存映射文件,并使用 ReadFileFILE_FLAG_NO_BUFFERING 标志。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2016-08-06
      • 2012-08-07
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多