Can I use ' == ' to compare two vectors. I tried it and seems to be working fine. But I don't know whether it will work in more complex situations

suman shadow picture suman shadow · May 7, 2013 · Viewed 51.4k times · Source

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 

Answer

Andy Prowl picture Andy Prowl · May 7, 2013

The overload of operator == that works on two std::vectors 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.