Quy Nguyen
Quy Nguyen

Reputation: 5

comparing each element of one vector to another's

So I am a novice c++ learner. I just got through the first 4 chapters in the "Principles and Practice using C++" (2nd edition). There is a problem in a book basically asking me to read in a sentence than filter it to "bleeps" out the words I don't like. So my idea is that first I read in whatever word I don't like to see to a vector, then I read in a sentence or so in another vector to print out later. And then I try to compare each of the element of the "print out" vector to the "disliked" vector, if they are the same, I'll rewrite it into "beep". But I can't figure out how write the code. Can anyone help me? and if my thinking is wrong, is there any easier way to do this? Thank you

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS
#include "../../../std_lib_facilities.h"
int main()
{   
vector<string> disliked;
cout << "Enter the disliked words: ";
for (string dword; cin >> dword;)
    disliked.push_back(dword);//inserting words to vector that's used to 
                                 //compare with

vector<string> words;
cout << "Enter words: \n";
for (string word; cin >> word;)
    words.push_back(word);
cout << "Number of words: " << words.size() << '\n';//inserting words to 
                                              //vector in order to print out

for (int x = 0, y = 0; x < words.size() , y < disliked.size(); x++, y++)
    if (words[x] = disliked[y])//this part is where it says it's wrong
        words[x] = "beep";


sort(words.begin(),words.end());

for (int i = 0; i < words.size(); i++)
    if (i == 0 || words[i - 1] != words[i])
        cout << words[i]<<'\n'; //not show repeated words

Upvotes: 0

Views: 970

Answers (1)

Chandini
Chandini

Reputation: 550

The program is stopping after the for loop of reading in disliked words because the condition in the for loop "cin>>word" is not actually enough, it will take any char or string you type, so all the words which you are entering are being pushed into the disliked vector itself.

So change the condition to something like, stop the for loop when the user gives the string "END" or something.

for (string dword; cin >> dword && dword!="END";)
      disliked.push_back(dword);

And also the below part of code is wrong,

for (int x = 0, y = 0; x < words.size() , y < disliked.size(); x++, y++)
{
  if (words[x] = disliked[y])//this part is where it says it's wrong
     words[x] = "beep";
 }

You need to check every string of disliked vector to every string of words vector. The comparing should be something like this.

 for (int x = 0; x < words.size() ; x++)
 {
   for(int y=0;y<disliked.size();y++)
  {
    if (words[x] == disliked[y])
    words[x] = "beep";
  }
}

Upvotes: 1

Related Questions