This tutorial will discuss about a unique way to check if an array is symmetric in C++.
Suppose we have an array,
int arr[] = {7, 6, 5, 4, 3, 4, 5, 6, 7};
Now we want to check if this array is Symmetrical or not.
To check if an array is symmetric or not, we need to compare the first half of the array with the reverse second half of array.
For this, we are going to use the std::equal()
function from STL. In this function, we will pass three arguments,
Frequently Asked:
- A pointer, pointing to the start of array i.e.
arr
. - A pointer pointing to the middle of the array i.e.
arr + len/2
. Where,len
is the size of array. - A reverse iterator pointing to the end of array i.e.
std::reverse_iterator<int*>(arr + len)
.
The std::equal()
function will compare the first half of the array, with the second half of array, but in the reverse direction because we have passed the reverse iterator as a 3rd argument. If the std::equal()
function returns true
, then that means the array arr
is symmetrical.
Let’s see the complete example,
#include <iostream> #include <algorithm> int main() { int arr[] = {7, 6, 5, 4, 3, 4, 5, 6, 7}; // Get the length of array size_t len = sizeof(arr)/sizeof(arr[0]); // Compare the first half of array with the // reversed second half of array bool result = std::equal(arr, arr + len/2, std::reverse_iterator<int*>(arr + len)); // Check if array is Symmetrical or not if(result) { std::cout<< "Yes, Array is Symmetric." << std::endl; } else { std::cout<< "No, Array is not Symmetric" << std::endl; } return 0; }
Output :
Yes, Array is Symmetric.
Summary
Today we learned about a way to check if an array is symmetric in C++. Thanks.