[英]comparing each element of one vector to another's
所以我是新手C ++學習者。 我剛讀完“使用C ++的原理和實踐”(第二版)的前4章。 一本書中存在一個問題,基本上是要求我讀一個句子,而不是過濾它以使我不喜歡的單詞“消失”。 所以我的想法是,首先我用我不希望看到的任何單詞讀到矢量,然后再讀一個句子或其他矢量,以便稍后打印。 然后,我嘗試將“打印出”向量的每個元素與“不喜歡的”向量進行比較,如果它們相同,則將其重寫為“嗶”聲。 但是我不知道怎么寫代碼。 誰能幫我? 如果我的想法是錯誤的,還有沒有更簡單的方法可以做到這一點? 謝謝
#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
在for循環中讀取不喜歡的單詞后,程序將停止,因為for循環“ cin >> word”中的條件實際上還不夠,它將占用您鍵入的任何字符或字符串,因此您輸入的所有單詞都是被推入不喜歡的向量本身。
因此,將條件更改為類似,當用戶提供字符串“ END”或其他內容時,停止for循環。
for (string dword; cin >> dword && dword!="END";)
disliked.push_back(dword);
而且下面的代碼部分是錯誤的,
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";
}
您需要檢查每個不喜歡的向量的字符串到單詞向量的每個字符串。 比較應該是這樣的。
for (int x = 0; x < words.size() ; x++)
{
for(int y=0;y<disliked.size();y++)
{
if (words[x] == disliked[y])
words[x] = "beep";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.