【问题标题】:comparing each element of one vector to another's将一个向量的每个元素与另一个向量的每个元素进行比较
【发布时间】: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


【解决方案1】:

程序在读取不喜欢的单词的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";
  }
}

【讨论】:

  • 这正是我所需要的。我很感激。
猜你喜欢
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
相关资源
最近更新 更多