vendredi 4 novembre 2016

How to loop through multiple condition IF statement in C++

I am a newbie in programming and I wrote a piece of code that works, but I am interested in making it scalable.

The following code checks if a single word from a vector list matches with any of the words in another vector list.

            if (words[i] != dislike[0] && words[i] != dislike[1] && words[i] != dislike[2] && words[i] != dislike[3])  //check for disliked words
                cout << words[i] << '\n';

As visibile, the code does the job by iterating word by word, so if I were to change the nubmer of words in my second vector list, I will need to add it to the IF statement.

Is there a more optimal solution? I have been trying to figure this out for hours, however I had no luck. Thanks.

P.S. Below is my full code.

int main()
{
    // words we dislike
    vector<string>dislike = { "broccoli", "coke", "potatoes", "water" };

    //take input from user
    vector<string> words;
    for (string temp; cin >> temp; ) // read whitespace-separated words
        words.push_back(temp); // put into vector

    //give output
    cout << "Number of words: " << words.size() << '\n';
    //sort(words); // DONT sort the words
    for (int i = 0; i<words.size(); ++i) //go through your words vector
    {
        if (i == 0 || words[i - 1] != words[i])//remove repeating words
        {           
            if (words[i] != dislike[0] && words[i] != dislike[1] && words[i] != dislike[2] && words[i] != dislike[3])  //check for dislike
                cout << words[i] << '\n';
            else
                cout << "BlEEP!\n";   //print if word is disliked*/
        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire