我可以使用'=='来比较两个向量吗?我尝试了一下,似乎工作正常。但不知道在更复杂的情况下是否有效

问题描述 投票:0回答:6

第一个例子:

int main(){
    using namespace std;   
    vector<int> v1{10, 20, 30, 40, 50};
    vector<int> v2{10, 20, 30, 40, 50};

    if(v1==v2)
        cout<<"equal";
    else
        cout<<"unequal";
}   // it returns equal 

第二个例子:

int main(){
    using namespace std;   
    vector<int> v1{10, 20, 30, 40, 50};
    vector<int> v2{10, 20, 100000, 40, 50};

    if(v1==v2)
        cout<<"equal";
    else
        cout<<"unequal";
}   // it returns notequal 
c++ vector equality
6个回答
99
投票

作用于两个operator ==

s
std::vector
重载将比较向量大小,如果不同则返回
false
;如果不是,它将逐个元素比较向量的内容。

如果为向量的元素类型定义了

operator ==
,则通过
operator ==
进行的向量比较是有效且有意义的。

在正式术语中,C++11 标准将序列容器的

a == b
操作语义指定为(表 96,第 23.2.1 节):

==
是等价的 关系。

distance(a.begin(), a.end()) == distance(b.begin(), b.end()) && equal(a.begin(), a.end(), b.begin())

如您所见,序列容器之间的相等性是根据迭代器对定义的范围之间的

std::equal
算法定义的,而迭代器又使用
operator ==
来比较各个元素。


9
投票

是的,您可以使用

operator==
来比较两个
std::vector
。仅当向量大小相同并且所有元素比较相等时,它才会返回
true


7
投票

请注意,向量是有序的,并且

std::equal
==
运算符检查向量是否具有相同顺序的相同内容。对于许多用例来说,这可能就足够了。

但是有时您可能想知道两个向量是否具有相同的内容但不一定具有相同的顺序。对于这种情况,您需要另一个功能。

下面是一个不错且简短的实现。 这里建议:https://stackoverflow.com/questions/17394149/how-to-efficiently-compare-vectors-with-c/17394298#17394298 在那里您还会找到关于为什么您可能不想使用它的讨论...

将其放入您选择的头文件中:

#include <algorithm>

template <class T>
static bool compareVectors(std::vector<T> a, std::vector<T> b)
{
   if (a.size() != b.size())
   {
      return false;
   }
   ::std::sort(a.begin(), a.end());
   ::std::sort(b.begin(), b.end());
   return (a == b);
}

这里有一个例子来说明上述理论:

std::vector<int> vector1;
std::vector<int> vector2;

vector1.push_back(100);
vector1.push_back(101);
vector1.push_back(102);

vector2.push_back(102);
vector2.push_back(101);
vector2.push_back(100);

if (vector1 == vector2)
   std::cout << "same" << std::endl;
else
   std::cout << "not same" << std::endl;

if (std::equal(vector1.begin(), vector1.end(), vector2.begin()))
   std::cout << "same" << std::endl;
else
   std::cout << "not same" << std::endl;

if (compareVectors(vector1, vector2))
   std::cout << "same" << std::endl;
else
   std::cout << "not same" << std::endl;

输出将是:

not same
not same
same

2
投票

您可以查看

operator==
的向量文档: operator==,!=,<,<=,>,>=(std::vector)

引用链接:

 template< class T, class Alloc >
 bool operator==( vector<T,Alloc>& lhs,
             vector<T,Alloc>& rhs );

比较两个容器的内容。

检查 lhs 和 rhs 的内容是否相等,即 lhs.size() == rhs.size() 以及 lhs 中的每个元素在 rhs 中的相同位置是否有等效元素。

参数:

lhs、rhs 容器,其内容进行比较

T 必须满足 EqualityComparable 的要求才能使用版本

返回值

如果容器的内容相同则为 true,否则为 false


2
投票

是的。 cppreference.com 是一个很好的参考,您可以在其中查找

operator==
中的
vector<T>
,例如在此页面上:非成员运算符,您会发现:

检查lhs和rhs的内容是否相等,即是否 lhs.size() == rhs.size() 并且 lhs 中的每个元素都有等效的 rhs 中相同位置的元素。


1
投票

只要你的向量包含本身可以比较的元素(有

operator==
),这就有效,是的。但请注意,如果您有一个向量,其中包含例如指向相同对象的指针,但不包含对象的 SAME 实例,则该向量不会被视为相同,因为比较的是向量中的元素,而不是对象的内容。元素本身,如果这有意义的话。

© www.soinside.com 2019 - 2024. All rights reserved.