This post will discuss how to check if two vectors contain the same elements in C++. The solution should compare two vectors for equality, ignoring the order.

1. Using std::sort

The idea is to sort both vectors and compare them using the == operator (or std::equal). The == operator checks whether the contents of both vectors are the same or not. The time complexity of this solution is O(n*log(n)), where n is the size of the vector.

Download  Run Code

2. Using std::is_permutation

Another viable alternative is to use the std::is_permutation function, which checks whether the specified range is a permutation of another range. This function is introduced with C++11 and performs at most O(n2) comparisons.

Download  Run Code

 
Alternatively, we can use the boost::algorithm::is_permutation function from the boost library. It checks if a sequence is a permutation of another one, i.e., it contains all the same elements in the same or different order.

Download Code

3. Using std::unordered_multiset

Finally, we can construct a multiset from each vector, and compare them for equality using the == operator. Since a set eliminates duplicates, a multiset should be used.

Download  Run Code

That’s all about checking if two vectors contain the same elements in C++.