enzom83
enzom83

Reputation: 8310

What is the difference between these two ways to compare STL vectors?

Few examples available online use the equality operator to compare the contents of two STL vector objects in order to verify that they have the same content.

vector<T> v1;
// add some elements to v1

vector<T> v2;
// add some elements to v2

if (v1 == v2) cout << "v1 and v2 have the same content" << endl;
else cout << "v1 and v2 are different" << endl;

Instead, I read other examples where the std::equal() function is used.

bool compare_vector(const vector<T>& v1, const vector<T>& v2)
{
    return v1.size() == v2.size()
           && std::equal(v1.begin(), v1.end(), v2.begin());
}

What is the difference between these two ways to compare STL vectors?

Upvotes: 5

Views: 229

Answers (2)

Pete Becker
Pete Becker

Reputation: 76245

Good question. I suspect that people don't use == because they don't know its there, but it does exactly what the hand-coded version does. It's always been there for sequence containers and for associative containers.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 476950

The two behave in exactly the same way. The container requirements (Table 96) say that a == b has the operational semantics of:

distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
equal(a.begin(), a.end(), b.begin())

Upvotes: 8

Related Questions