我是新手,使用Bjarne Stroustrup的编程原理...学习C ++。我正在解决一个问题,无法弄清楚如何使我的代码工作。我知道问题出在if (words[i]==bad[0, bad.size() - 1])
,特别是bad.size() - 1])
我试图将所有单词放在单词向量中,除了显示哔哔声而不是单词向量中与错误向量中的任何单词匹配的任何单词。所以我需要知道单词[i]是否匹配坏向量中的任何值。
#include "../std_lib_facilities.h"
using namespace std;
int main()
{
vector<string> words; //declare Vector
vector<string> bad = {"idiot", "stupid"};
//Read words into Vector
for(string temp; cin >> temp;)
words.push_back(temp);
cout << "Number of words currently entered "
<< words.size() << '\n';
//sort the words
sort(words);
//read out words
for(int i = 0; i < words.size(); ++i)
if (i==0 || words[i-1]!= words[i])
if (words[i]==bad[0, bad.size() - 1])
cout << "Bleep!\n";
else
cout << words[i] << '\n';
return 0;
}
答案 0 :(得分:0)
您需要浏览bad
向量中words
向量中每个条目的所有条目。像这样:
for(const string& word : words)
{
bool foundBadWord = false;
for(const string& badWord : bad)
{
if(0 == word.compare(badWord))
{
foundBadWord = true;
break;
}
}
if(foundBadWord)
{
cout << "Bleep!\n";
}
else
{
cout << word << "\n";
}
}