Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

Is there any way to compare two vectors?

if (vector1 == vector2)     DoSomething(); 

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

like image 732
Jame Avatar asked Jun 06 '11 05:06

Jame


People also ask

What does the equality operator do with two vectors?

Description. 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 we use == in vector?

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

How do you check if all elements in a vector are equal?

A simple solution to check if all elements of a vector are equal is using the std::adjacent_find function. It returns the first occurrence of adjacent elements that satisfies a binary predicate, or end of the range if no such pair is found.


1 Answers

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(); 
like image 122
solvingPuzzles Avatar answered Oct 03 '22 11:10

solvingPuzzles