I would like to compare vector with an array. Elements in vector and in array are in different order, unsorted and can duplicated. E.g.
Below are the same:
vector<int> lvector = {5,7,3,1,2,7};
int larray[6] = {3,5,1,7,2,7}
Below, not the same:
vector<int> lvector = {5,7,3,1,2,7,5};
int larray[7] = {3,5,1,7,2,7,3}
And something like this is also not the same:
vector<int> lvector = {1,1,1,1,2,2};
int larray[6] = {1,1,1,1,1,2}
Now I need to check if vector and array have got the same elements. I can't modify the vector and the array, but I can create a new container and copy the element from vector and array to this new container and then copare them. I am asking about this, because I would like to do this in en efficient way. Thanks.
There are a lot of different ways of solving this problem, each has proc and cons.
Some pre-tests
xor
them all. Arrays with different hash value cannot be equal.std::unordered_multiset
You could create an
unordered_multiset
, which holds frequency of elements in the range. While it has linear complexity in average, it may be O(n^2) because of hash collisions. Quote from the Standard (N3337, § 23.5.7.2):However, you should also remember the complexity of
std::unordered_set::operator==
:Example:
std::sort
You could compare sorted copies of your range. According to the Standard (N3337, § 25.4.1.1) , it has
O(n * log(n))
complexity:Example: