【发布时间】:2017-05-26 02:55:35
【问题描述】:
所以我是一个新手 C++ 学习者。我刚读完“使用 C++ 的原理与实践”(第 2 版)的前 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
【问题讨论】:
-
在C++中
=是赋值,比较使用== -
您绝对应该启用编译器警告。
if语句中的赋值通常会被检测到。 -
哦,哈哈,这是一个如此简单的错误。谢谢你。现在我还有另一个问题。在输入“不喜欢”向量的信息后,会弹出另一个窗口并显示“已调用 abort()”。那么我该如何解决这个问题呢?
标签: c++ for-loop vector compare elements