C++ 如何在C++中逐个元素比较两个向量的相等性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6248044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:46:12  来源:igfitidea点击:

How to compare two vectors for equality element by element in C++?

c++stdvector

提问by Jame

Is there any way to compare two vectors?

有没有办法比较两个向量?

if (vector1 == vector2)
    DoSomething();

Note:Currently, these vectors are not sorted and contain integer values.

注意:目前,这些向量未排序且包含整数值。

采纳答案by Jhaliya

Check std::mismatchmethod of C++.

std::mismatchC++的检查 方法。

comparing vectors has been discussed on DaniWeb forumand also answered.

比较向量已经在DaniWeb 论坛上讨论过,也得到了回答

C++: Comparing two vectors

C++:比较两个向量

Check the below SO post. will helpful for you. they have achieved the same with different-2 method.

检查下面的SO帖子。会对你有帮助。他们用不同的 2 方法实现了相同的效果。

Compare two vectors C++

比较两个向量 C++

回答by solvingPuzzles

Your code (vector1 == vector2) is correct C++ syntax. There is an ==operator for vectors.

您的代码 ( vector1 == vector2) 是正确的 C++ 语法。有一个==向量运算符。

If you want to compare short vector with a portion of a longer vector, you can use theequal()operator for vectors. (documentation here)

如果要将短向量与较长向量的一部分进行比较,可以使用equal()向量运算符。(文档在这里

Here's an example:

下面是一个例子:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
    DoSomething();

回答by Shahrukh Haider

According to the discussion hereyou can directly compare two vectors using

根据这里的讨论您可以使用直接比较两个向量

==

==

if (vector1 == vector2){
   //true
}
else{
   //false
}

回答by Shahrukh Haider

If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.

如果他们真的绝对必须保持未排序(他们真的没有......如果你正在处理数十万个元素,那么我不得不问你为什么要比较这样的向量),你可以将一个比较适用于未排序数组的方法。

The only way I though of to do that was to create a temporary vector3and pretend to do a set_intersectionby adding all elements of vector1to it, then doing a search for each individual element of vector2in vector3and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.

我想这样做的唯一方法是创建一个临时对象vector3并假装set_intersection通过向其中添加所有元素vector1来执行 a,然后搜索vector2in 的每个单独元素,vector3如果找到则将其删除。我知道这听起来很糟糕,但这就是为什么我不会很快编写任何 C++ 标准库。

Really, though, just sort them first.

不过,实际上,只需先对它们进行排序。