How to compare two vectors for equality element by element in C++?

Jame picture Jame · Jun 6, 2011 · Viewed 140.3k times · Source

Is there any way to compare two vectors?

if (vector1 == vector2)
    DoSomething();

Note: Currently, these vectors are not sorted and contain integer values.

Answer

solvingPuzzles picture solvingPuzzles · Sep 29, 2012

Your code (vector1 == vector2) is correct C++ syntax. There is an == operator for vectors.

If you want to compare short vector with a portion of a longer vector, you can use theequal() operator for vectors. (documentation here)

Here's an example:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
    DoSomething();