To check if two arrays are equal in C++, you can use the std::equal
algorithm for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.std::equal
algorithm to check if the arrays are equal and store the result in the variable equal1
.std::equal
algorithm compares the elements of two sequences and returns true
if they are equal; otherwise, false
.equal1
to the console.#include <iostream>
#include <algorithm>
#include <array>
int main() {
std::array<int, 3> arr1 = {1, 2, 3};
std::array<int, 3> arr2 = {1, 2, 3};
bool equal1 = std::equal(arr1.begin(), arr1.end(), arr2.begin());
std::cout << "Arrays are equal: " << std::boolalpha << equal1 << std::endl;
return 0;
}
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.equal2
.equal2
is set to true
; otherwise, it's set to false
.equal2
to the console.#include <iostream>
#include <array>
int main() {
std::array<int, 3> arr3 = {1, 2, 3};
std::array<int, 3> arr4 = {3, 2, 1};
bool equal2 = true;
for (int i = 0; i < arr3.size(); i++) {
if (arr3[i] != arr4[i]) {
equal2 = false;
break;
}
}
std::cout << "Arrays are equal: " << std::boolalpha << equal2 << std::endl;
return 0;
}
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in C++ language with well detailed examples.