Q:

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

Write a program that “bleeps” out words that you don’t like; that is, you read in words using cin and print them
again on cout. If a word is among a few you have defined, you write out BLEEP instead of that word. Start with
one “disliked word” such as
string disliked = “Broccoli”;
When that works, add a few more.
So i was thinking on how i could create a code that would do that with a set of words using a vector, but all i could come up with was
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 << "Bleep\n";
        else
            cout << word << "\n";
    }

    return 0;
}

i feel like that code can be shortened with taking out one of the if statements but i can't find a working way to do it.
overall it seems like more code than it should be for this simple check, also could  the for part be done better? doing a whole loop of the whole vector seems to be too resource intensive in a case where the vector has lets say a 1000 words, maybe separating it by an if statement checking for a-d, f-j... etc, and then only running a for loop would be less heavy?

A:

Sort your vector and use 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;
        }
    }
}

or use std::set instead of vector:
#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;
        }
    }
}

Both of these solutions have logarithmic complexity for the word lookup instead of linear.

