为什么比较运算符"=="返回"YES"即使两个向量不同?

Why is comparison operator "==" returning "YES" even though the two vectors are different?

本文关键字:两个 向量 运算符 比较 返回 YES 为什么      更新时间:2023-10-16

我尝试运行这段代码,结果显示"是"甚至认为两个向量具有不同的内容并且大小不同。我不明白比较运算符如何处理向量

#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);

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