Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

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?

like image 520
enzom83 Avatar asked Mar 06 '13 23:03

enzom83


People also ask

How do you compare vectors?

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.

What is the difference between std :: vector and std :: list?

Vector may have a default size. List does not have default size. In vector, each element only requires the space for itself only. In list, each element requires extra space for the node which holds the element, including pointers to the next and previous elements in the list.

Which is better list or vector?

In general, use vector when you don't care what type of sequential container that you're using, but if you're doing many insertions or erasures to and from anywhere in the container other than the end, you're going to want to use list. Or if you need random access, then you're going to want vector, not list.


1 Answers

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())
like image 196
Kerrek SB Avatar answered Nov 05 '22 15:11

Kerrek SB