Home > database >  Compare two unsorted std::vector
Compare two unsorted std::vector

Time:12-17

What is the best way to compare two unsorted std::vector

std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {2, 3, 4, 5, 1};

What I am currently doing is

const auto is_similar = v1.size() == v2.size() && std::is_permutation(v1.begin(), v1.end(), v2.begin());

Here two vectors are similar only when the size of both vectors are equal and they contain the same elements

What would be a better approach for

  • two small std::vectors (size well under 50 elements)
  • two large std::vectors

CodePudding user response:

What would be a better approach

Remove the v1.size() == v2.size() && expression and instead pass end iterator to std::is_permutation.

You tagged C 11, but to those who can use C 20, I recommend following:

std::ranges::is_permutation(v1, v2)

If you can modify the vectors, then it will be asymptotically faster to sort them and compare equality. If you cannot modify, then you could create a sorted copy if you can afford the storage cost.

  • Related