Alex Rivera | Logout

Check if two vectors are equal

Asked 2011-03-08T04:15:42.950
55

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

Edit
Report

1 Answer

7

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/

answered 2011-03-08T04:21:34.473

Your Answer