本文介绍了检查两个向量是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查两个向量的第一个n元素是否相等?

How can I check whether the first "n" elements of two vectors are equal or not?

我尝试了以下操作:

#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"?

推荐答案

使用函数:

Use the std::equal function from the <algorithm> header:

if (std::equal(v1.begin(), v1.begin() + n, v2.begin())
  std::cout << "success" << std::endl;

在其中至少有 n 个元素,如果任一个太短,您的程序的行为将是未定义的。

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.

如果您想要检查整个向量是否等于另一个,只需比较它们,就像您比较任何其他:

If you want to check whether the entire vector is equal to the other, just compare them like you'd compare anything else:

if (v1 == v2)

比较一个向量的迭代器和另一个向量的迭代器。等向量的迭代器不相等,每个迭代器都与迭代的序列相关,向量永远不会等于另一个的迭代器。

Your (failed) code was comparing an iterator of one vector with an iterator of 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.

这篇关于检查两个向量是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 16:54