Two vectors are said to equal if all the elements at every index of vectors is equal. In this article, we will learn how to check if two vectors are equal or not in C++.
The simplest method to check if two vector are equal is by using comparison operator (==). Let’s take a look at an example:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {1, 3, 5};
// Checking vectors are equal or not
if (v1 == v2)
cout << "Equal";
else
cout << "NOT Equal";
return 0;
}
Output
Equal
Note: Comparison operator will only work, if the data type of both vectors are same. Otherwise it will give error.
There are also some other methods in C++ by which we can check whether two vectors are equal or not. Some of them are as follows:
Table of Content
Using equal()
If the data type and size of both vectors are same, then we can use equal() method to check the equality of vector.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {1, 3, 3};
// Checking vectors are equal or not
if (equal(v1.begin(), v1.end(), v2.begin()))
cout << "Equal";
else
cout << "NOT Equal";
return 0;
}
Output
NOT Equal
Note: This method will work properly only if the data type and size of both vectors are same.
Manually Using Loop
To check the equality of two vectors, iterate through both vectors and compare the elements at each index. If all elements match, the vectors are equal. otherwise, they are not.
#include <bits/stdc++.h>
using namespace std;
bool isEqual(vector<int> &v1, vector<int> &v2) {
// If size is different
if (v1.size() != v2.size()) return false;
// Checking all elements of vector equal or not
for (int i = 0; i < v1.size(); i++) {
if (v1[i] != v2[i]) return false;
}
return true;
}
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {1, 3, 5};
if (isEqual(v1, v2)) cout << "Equal";
else cout << "NOT Equal";
return 0;
}
Output
Equal
Using mismatch()
To check the equality of two vectors, the mismatch() method can be used. It returns a pair of iterators pointing to the first differing positions in both vectors. If both iterators reach the end of their respective vectors, then they are equal. Otherwise, they are not.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5, 7, 9};
vector<int> v2 = {1, 3, 5};
// Finding first position where they differ
auto p = mismatch(v1.begin(), v1.end(), v2.begin());
// Checking Vectors equal or not
if (p.first == v1.end() && p.second == v2.end())
cout << "Vectors are Equal";
else
cout << "Vectors are NOT Equal";
return 0;
}
Output
Vectors are Equal