如何使我的单词查找更清晰、更高效

How can I make my word lookup cleaner and more efficient?

本文关键字:清晰 高效 查找 何使 我的 单词      更新时间:2023-10-16

编写一个程序,"哔哔"出你不喜欢的单词;也就是说,你用cin阅读单词并打印出来再次在库特。如果一个词是你定义的几个词之一,你写出BLEEP而不是那个词。入手一个"不喜欢的词",例如不喜欢的字符串="西兰花";当它有效时,再添加一些。

所以我在考虑如何创建一个代码,使用向量用一组单词来做到这一点,但我能想到的只是

int main()
{
    vector<string> disliked = { "damn","stupid","fat" };
    string word = "";
    while (cin >> word) {
        bool bad = false;
        for (string x : disliked) {
            if (x == word)
                bad = true;
        }
        if (bad)
            cout << "Bleepn";
        else
            cout << word << "n";
    }

    return 0;
}

我觉得可以通过取出其中一个 if 语句来缩短该代码,但我找不到一种方法来做到这一点。总的来说,对于这个简单的检查,代码似乎比应该的要多,对于部分也可以做得更好吗?在向量有 1000 个单词的情况下,对整个向量进行整个循环似乎过于资源密集,也许可以通过检查 a-d、f-j 的 if 语句将其分开......等等,然后只有运行一个 for 循环会不那么重?

对向量进行排序并使用std::binary_search

#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
    std::vector<std::string> disliked = { "damn","stupid","fat" };
    sort(std::begin(disliked), std::end(disliked));
    std::string word = "";
    while (std::cin >> word)
    {
        if ( binary_search(std::begin(disliked), std::end(disliked), word))
        {
            std::cout << "Bleep ";
        }
        else
        {
            std::cout << word;
        }
    }
}

或使用std::set而不是矢量:

#include <iostream>
#include <set>
#include <algorithm>
int main()
{
    std::set<std::string> disliked = { "damn","stupid","fat" };
    std::string word = "";
    while (std::cin >> word)
    {
        if ( disliked.find(word) != std::end(disliked) )
        {
            std::cout << "Bleep ";
        }
        else
        {
            std::cout << word;
        }
    }
}

这两种解决方案对于单词查找而不是线性都具有对数复杂性。

对向量使用 std::find 运算。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector<string> disliked = { "damn","stupid","fat" };
    string word = "";
    while (cin >> word) {
        if ( std::find(disliked.begin(), disliked.end(), word) != disliked.end() )
        {
            cout << "Bleep ";
        }
        else
        {
            cout << word;
        }
    }
   return 0;
}