c++ - 为什么即使两个向量不同,比较运算符“==”也会返回“YES”?
问题描述
我尝试运行此代码,结果显示“是”,即使这两个向量具有不同的内容并且具有不同的大小。我不明白比较运算符如何与向量一起使用
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> example; //First vector definition
example.push_back(3);
example.push_back(10);
example.push_back(33);
for(int x=0;x<example.size();x++)
{
cout<<example[x]<<" ";
}
if(!example.empty())
{
example.clear();
}
vector <int> another_vector; //Second vector definition
another_vector.push_back(10);
example.push_back(10);
if(example==another_vector) //Comparison between the two vector
{
cout<<endl<<"YES";
}
else
{
cout<<endl<<"NO";
}
return 0;
}
预期的输出是“否”但收到的输出是“是”
解决方案
在这里,您将删除所有元素example
:
if(!example.empty())
{
example.clear();
}
因此,此时第一个向量为空。然后,您创建another_vector
,默认为空。现在,
another_vector.push_back(10);
example.push_back(10);
此时,两个向量都只包含一个元素:10
。operator ==
做它应该做的事情。
推荐阅读
- java - 将一个面板类的按钮连接到另一个面板类的数据
- makefile - make 无法编译 Vc 库
- python-3.x - 安装 nltk 包时出现 ModuleNotFoundError: No module named '_sqlite3'
- asp.net-mvc - 如何在 azure 上使用 asp.net mvc 结构部署 Angular 5
- ruby-on-rails - 在rspec中创建回调后的gettig弃用警告
- javascript - Mozilla中的Javascript剪贴板SetData错误
- dom - Electron:DevTools 让应用程序更快?
- angular - 使用模拟商店时如何在ngxs中模拟@Select
- ruby - 截取字符串的最后一个字符
- tensorflow - Tensorflow:tf.contrib.slim 和 tf.layers 之间的区别