To check if two arrays have the same elements regardless of order in C++, you can use the std::sort
algorithm to sort both arrays and then compare them element by element.
In this example,
iostream
and algorithm
.arr1
and arr2
with the same elements but in different order.std::sort
algorithm.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.#include <iostream>
#include <algorithm>
#include <vector>
bool arraysEqual(std::vector<int>& arr1, std::vector<int>& arr2) {
std::sort(arr1.begin(), arr1.end());
std::sort(arr2.begin(), arr2.end());
return arr1 == arr2;
}
int main() {
std::vector<int> arr1 = {1, 2, 3};
std::vector<int> arr2 = {3, 1, 2};
bool isEqual = arraysEqual(arr1, arr2);
std::cout << (isEqual ? "true" : "false") << std::endl;
return 0;
}
true
In this example,
iostream
and algorithm
.arr3
and arr4
with different elements.std::sort
algorithm.arraysEqual
that checks if the sorted arrays are equal.arraysEqual
to compare the arrays and print the result to the console.#include <iostream>
#include <algorithm>
#include <vector>
bool arraysEqual(std::vector<int>& arr1, std::vector<int>& arr2) {
std::sort(arr1.begin(), arr1.end());
std::sort(arr2.begin(), arr2.end());
return arr1 == arr2;
}
int main() {
std::vector<int> arr3 = {1, 2, 3};
std::vector<int> arr4 = {4, 5, 6};
bool isEqual = arraysEqual(arr3, arr4);
std::cout << (isEqual ? "true" : "false") << std::endl;
return 0;
}
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in C++ language with well detailed examples.