EQUAL()
This is used to compare two sequences (such as arrays, vectors, or other containers) to determine if they contain the same elements in the same order. It returns true
if all corresponding elements in both ranges are equal, and false
otherwise. The function typically takes two iterators defining the first range, and another iterator pointing to the start of the second range. By default, std::equal()
uses the equality operator (==
) to compare elements, but you can also provide a custom binary predicate (a function or lambda) to define a different comparison condition. It’s often used for validating that two containers are identical or for verifying that a subset of elements matches another range.
#include <algorithm> // For equal
#include <iterator> // For begin() and end()
bool areEqual = equal(begin(array1), end(array1), begin(array2));
* begin(array1) – Starting address of the first array
* end(array1) – One past the last element of the first array
* begin(array2) – Starting address of the second array
#include <iostream>
#include <algorithm> // For equal
#include <iterator> // For begin(), end()
using namespace std;
int main() {
// Declare and initialize two arrays of integers
int array1[] = {1, 2, 3, 4}; // Array 1
int array2[] = {1, 2, 3, 4}; // Identical to array1
// Compare array1 and array2 using equal
bool areEqual = equal(begin(array1), end(array1), begin(array2));
// Output the result of the comparison
if (areEqual) {
cout << "Array1 and Array2 are equal: Yes" << endl;
} else {
cout << "Array1 and Array2 are equal: No" << endl;
}
return 0;
}
OUTPUT:
Array1 and Array2 are equal: Yes
Last updated