【问题标题】:Spell-Checker c++; checking whether the word is in the dictionary text拼写检查器 C++;检查单词是否在字典文本中
【发布时间】:2018-03-22 19:04:44
【问题描述】:

我是这个地方的新手,所以我可能不会清楚地问我的问题。但我确实需要帮助。所以我的作业是用 C++ 创建一个拼写检查器,它接受一个文本文件并将其与另一个字典文本文件进行比较。我有一个特定的 sn-p 代码需要解决。我创建了一个帮助函数 isValidWord,它接收包含容器 unordered_set 和字符串的字典。如果字符串与字典中的单词匹配,该函数将返回 true。我只会告诉你我到目前为止所拥有的。我的问题是字符串与库中的所有内容都不匹配,只检查字典中的一些内容。

#include <unordered_set>
#include <string>
bool isValidWord(std::unordered_set<std::string> dictionary, std::string& word) {
        std::unordered_set<std::string>::iterator it;
        for (it = dictionary.begin(); it != dictionary.end(); ++it) {
            if (word == *it) {
                return true;
            }
        }
        return false;
    }

【问题讨论】:

  • 不匹配的原因与字母的CASE有关吗?
  • 你能展示一个字符串与所有内容都不匹配的示例输入吗?
  • @CodeGorilla 案例问题已经解决
  • @SebastianStern 当字典有 80k+ 个单词时,字符串只会检查字典中的 2 个单词
  • 请也通过引用传递字典,你不想通过值传递它bool isValidWord(std::unordered_set&lt;std::string&gt;&amp; dictionary...

标签: c++ string iterator unordered-set


【解决方案1】:

有一个内置的find method in unordered_set,您可以利用它而不是重新发明轮子。此外,通过引用传递dictionary 以避免无意义的复制也是一个好主意。

【讨论】:

    【解决方案2】:

    您可以使用以下方法简化您的方法(我添加了缺少的 const 和参考):

    bool isValidWord(const std::unordered_set<std::string>& dictionary,
                     const std::string& word)
    {
        return dictionary.count(word) != 0;
    }
    

    您当前的实现是正确的,但性能不佳:

    • 您通过副本传递您的字典(因此您每次都重新创建它)。
    • 您使用线性搜索,而容器提供更好的复杂性。 (std::unordered_set::findstd::unordered_set::count)。

    最后说明,如果你想检索所有无效的单词,你可以查看std::set_difference(需要对单词和字典进行排序)。

    【讨论】:

    • 这是一个优雅的sn-p代码。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2011-05-23
    • 2015-02-14
    • 2016-07-13
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多