C++ 检查两个向量是否相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5228269/
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
Check if two vectors are equal
提问by 0x0
How can I check whether the first "n" elements of two vectors are equal or not?
如何检查两个向量的前“n”个元素是否相等?
I tried the following:
我尝试了以下方法:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
typedef vector<double> v_t;
int main(){
v_t v1,v2;
int n = 9;
for (int i = 1; i<10; i++){
v1.push_back(i);
v2.push_back(i);
}
v1.push_back(11);
v2.push_back(12);
if (v1.begin()+n == v2.begin()+n)
cout << "success" << endl;
else
cout << "failure" << endl;
}
Why does it print "failure" and not "success"?
为什么它打印“失败”而不是“成功”?
回答by Rob Kennedy
Use the std::equal
function from the <algorithm>
header:
使用标题中的std::equal
函数<algorithm>
:
if (std::equal(v1.begin(), v1.begin() + n, v2.begin())
std::cout << "success" << std::endl;
Note that both vectors must have at least n
elements in them. If either one is too short, behavior of your program will be undefined.
请注意,两个向量中必须至少包含n
元素。如果任一太短,您的程序的行为将是未定义的。
If you want to check whether the entirevector is equal to the other, just compare them like you'd compare anything else:
如果你想检查整个向量是否等于另一个,只需像比较其他任何东西一样比较它们:
if (v1 == v2)
Your (failed) code was comparing an iteratorof one vector with an iteratorof the other. Iterators of equal vectors are not equal. Each iterator is tied to the sequence it's iterating, so an iterator from one vector will never be equal to the iterator of another.
您的(失败的)代码正在将一个向量的迭代器与另一个向量的迭代器进行比较。相等向量的迭代器不相等。每个迭代器都与其迭代的序列相关联,因此来自一个向量的迭代器永远不会等于另一个向量的迭代器。
回答by Tony Delroy
The easiest (in terms of fewest non-everyday functions to look up) way to compare the two is to loop again:
比较两者的最简单(就最少的非日常功能而言)方法是再次循环:
bool are_equal = true;
for (int i = 0; i < first_how_many; i++)
if (v1[i] != v2[i])
{
are_equal = false;
break;
}
It'll do much the same thing, but if you prefer you can use the <algorithm>
header's std::equal
function: http://www.cplusplus.com/reference/algorithm/equal/
它会做很多相同的事情,但如果你愿意,你可以使用<algorithm>
标题的std::equal
功能:http: //www.cplusplus.com/reference/algorithm/equal/