Check if two vectors are equal or not in C++
This post will check if two vectors are equal or not in C++.
Two vectors are said to be equal if they have the same contents in the same order. If two vectors have the same contents but in a different order, they are not equal to each other as results of the [] operator varies. There are many ways to check two vectors for equality in C++, which are discussed below. To check if two vectors contain the same contents but in a different order, sort both vectors before calling any of the following methods.
1. Using == operator
The simplest solution is to use the == operator that checks if the contents of the two containers are equal or not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (v1 == v2) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
Output:
Both vectors are not equal
2. Using std::equal function
We can also use the std::equal algorithm to determine whether elements in the two ranges are equal. This might fail if elements in the second sequence are more than in the first sequence. So, it is better to check if the size of both vectors is also the same.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> template<typename T> bool isEqual(std::vector<T> const &v1, std::vector<T> const &v2) { return (v1.size() == v2.size() && std::equal(v1.begin(), v1.end(), v2.begin())); } int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (isEqual(v1, v2)) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
Output:
Both vectors are not equal
3. Using std::mismatch function
Finally, the standard library offers the std::mismatch algorithm, which compares the elements in two specified range and returns a pair specifying the first position where they differ.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> template<typename T> bool isEqual(std::vector<T> const &v1, std::vector<T> const &v2) { auto pair = std::mismatch(v1.begin(), v1.end(), v2.begin()); return (pair.first == v1.end() && pair.second == v2.end()); } int main() { std::vector<int> v1 = { 1, 2, 5, 3, 4, 5 }; std::vector<int> v2 = { 1, 2, 3, 5, 4, 5 }; if (isEqual(v1, v2)) { std::cout << "Both vectors are equal"; } else { std::cout << "Both vectors are not equal"; } return 0; } |
Output:
Both vectors are not equal
That’s all about determining whether two vectors are equal or not in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)