First example:
int main(){ using namespace std; vector<int> v1{10, 20, 30, 40, 50}; vector<int> v2{10, 20, 30, 40, 50}; if(v1==v2) cout<<"equal"; else cout<<"unequal"; } // it returns equal
Second example:
int main(){ using namespace std; vector<int> v1{10, 20, 30, 40, 50}; vector<int> v2{10, 20, 100000, 40, 50}; if(v1==v2) cout<<"equal"; else cout<<"unequal"; } // it returns notequal
A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.
In simple words, we can say that two or more vectors are said to be equal vectors if their length is the same and they all point in the same direction. Generally, we can check for equal vectors by comparing their coordinates. If all the coordinates of two or more vectors are the same, then they are equal 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.
If the vectors are homogeneous, for example, images of different dimensions, then another approach is possible to compare them. It is necessary to compare a smaller vector with all fragments of a larger vector with similar lengths. In this case, a part of a larger vector may exactly coincide with a smaller vector.
The overload of operator ==
that works on two std::vector
s will compare the vector sizes and return false
if those are different; if not, it will compare the contents of the vector element-by-element.
If operator ==
is defined for the vector's element type, then the comparison of vectors through operator ==
is valid and meaningful.
In formal terms, the C++11 standard specifies the operational semantics of a == b
for sequence containers as (Table 96, § 23.2.1):
==
is an equivalence relation.
distance(a.begin(), a.end()) == distance(b.begin(), b.end()) && equal(a.begin(), a.end(), b.begin())
As you can see, equality between sequence containers is defined in terms of the std::equal
algorithm between ranges defined by pairs of iterators, which in turn uses operator ==
for comparison of individual elements.
Yes, you can use operator==
to compare two std::vector
s. It will return true
only if the vectors are the same size and all elements compare equal.
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