我是编程的新手,我编写了一段可行的代码,但我有兴趣使其可扩展。
以下代码检查矢量列表中的单个单词是否与另一个矢量列表中的任何单词匹配。
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';
作为visibile,代码通过逐字迭代来完成工作,所以如果我要在第二个向量列表中更改单词的nubmer,我需要将它添加到IF语句中。
有更优化的解决方案吗?我一直试图弄清楚这几个小时,但我没有运气。 感谢。
P.S。以下是我的完整代码。
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;
}
答案 0 :(得分:0)
这个怎么样?
添加另一个遍历所有for
向量的循环dislike
。
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
{
for(int j=0;j<dislike.size();j++)
{
int count = 0;
if (words[i] != dislike[j])count++;
if(count == dislike.size())cout << words[i] << '\n'; //check for dislike
else
cout << "BlEEP!\n"; //print if word is disliked*/
}
}
}
return 0;
}