Is there any way to compare two vectors?
if (vector1 == vector2) DoSomething();
Note: Currently, these vectors are not sorted and contain integer values.
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.
As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With