首页 > 解决方案 > 为什么即使两个向量不同,比较运算符“==”也会返回“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;
}

预期的输出是“否”但收到的输出是“是”

标签: c++stl

解决方案


在这里,您将删除所有元素example

if(!example.empty())
{
    example.clear();
}

因此,此时第一个向量为空。然后,您创建another_vector,默认为空。现在,

another_vector.push_back(10);
example.push_back(10);

此时,两个向量都只包含一个元素:10operator ==做它应该做的事情。


推荐阅读