Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two vectors are equal

Tags:

c++

set

vector

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

like image 501
0x0 Avatar asked Mar 08 '11 04:03

0x0


People also ask

How do you check if two vectors are equal in C++?

The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.

Can you use == on vectors C++?

As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.

Can you compare two vectors in C++?

Comparing two vectors using operator ==std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.


2 Answers

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.

like image 194
Rob Kennedy Avatar answered Oct 09 '22 14:10

Rob Kennedy


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/

like image 23
Tony Delroy Avatar answered Oct 09 '22 15:10

Tony Delroy