Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c++ - Check if two vectors are equal

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...