Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if two std::vector's contain only the same elements?

I need an algorithm or a standard library function for comparing two vector elements, like below:

class Utility
{
    template <class T>
    static bool CheckIfVectorsEquivalent(   const std::vector<T> & Vec1,
                                            const std::vector<T> & Vec2)
    {
        // ???
    }
};

Working under the following specifications:

std::vector<int> v1, v2, v3, v4, v5, v6, v7, v8;

// Returns false when not all the elements are matching between vectors
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v2.push_back(2);
v2.push_back(3);
v2.push_back(8);
Utility::CheckIfVectorsEquivalent(v1, v2);  // Must return false

// Returns true when all the elements match, even if the are not in the same order
v3.push_back(3);
v3.push_back(1);
v3.push_back(7);
v4.push_back(7);
v4.push_back(3);
v4.push_back(1);
Utility::CheckIfVectorsEquivalent(v3, v4);  // Must return true

// Returns false when one of the vectors is subset of the other one
v5.push_back(3);
v5.push_back(1);
v5.push_back(7);
v6.push_back(7);
v6.push_back(3);
v6.push_back(1);
v6.push_back(18);
v6.push_back(51);
Utility::CheckIfVectorsEquivalent(v5, v6);  // Must return false

// Returns true when the both vectors are empty
Utility::CheckIfVectorsEquivalent(v7, v8);  // Must return true

Is there any standard (with STL) way of doing this? If not, how can I write this algorithm? It confused me too much.

like image 533
hkBattousai Avatar asked May 08 '12 21:05

hkBattousai


1 Answers

The standard way will be sorting these two vectors and using operator ==, which compares corresponding values.

The sample solution realizing this algorithm is:

#include <vector>
#include <algorithm>

template<typename T>
bool compare(std::vector<T>& v1, std::vector<T>& v2)
{
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
    return v1 == v2;
}

Its complexity is O(n*log(n)), because of the sorting.

like image 117
Rafał Rawicki Avatar answered Oct 04 '22 20:10

Rafał Rawicki