我可以使用'=='来比较两个向量.我试过了,似乎工作正常.但我不知道它是否适用于更复杂的情况

sum*_*dow 44 c++ equality vector operator-overloading

第一个例子:

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 
Run Code Online (Sandbox Code Playgroud)

第二个例子:

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 
Run Code Online (Sandbox Code Playgroud)

And*_*owl 65

在两个s 上工作重载operator ==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 ==用于比较各个元素.


小智 8

请注意,向量是有序的,并且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);
}
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

输出将是:

not same
not same
same
Run Code Online (Sandbox Code Playgroud)


Jos*_*eld 7

是的,你可以operator==用来比较两个std::vector.true仅当向量大小相同且所有元素相等时,它才会返回.