Be advised that vectors are ordered, and std::equal
or the ==
operator check that the vectors have the same contents in the same order. For many use cases this might be enough.
But there might be occasions when you want to know if two vectors have the same contents but not necessarily in the same order. For that case you need another function.
One nice and short implementation is the one below.
It was suggested here: https://stackoverflow.com/questions/17394149/how-to-efficiently-compare-vectors-with-c/17394298#17394298
There you will also find a discussion on why you might not want to use it...
Put this in a header file of your choice:
#include <algorithm>
template <class T>
static bool compareVectors(std::vector<T> a, std::vector<T> b)
{
if (a.size() != b.size())
{
return false;
}
::std::sort(a.begin(), a.end());
::std::sort(b.begin(), b.end());
return (a == b);
}
And here an example illustrating the above theory:
std::vector<int> vector1;
std::vector<int> vector2;
vector1.push_back(100);
vector1.push_back(101);
vector1.push_back(102);
vector2.push_back(102);
vector2.push_back(101);
vector2.push_back(100);
if (vector1 == vector2)
std::cout << "same" << std::endl;
else
std::cout << "not same" << std::endl;
if (std::equal(vector1.begin(), vector1.end(), vector2.begin()))
std::cout << "same" << std::endl;
else
std::cout << "not same" << std::endl;
if (compareVectors(vector1, vector2))
std::cout << "same" << std::endl;
else
std::cout << "not same" << std::endl;
The output will be:
not same
not same
same