How to reverse an Array using STL in C++?

C++Server Side ProgrammingProgramming

Here we will see how to reverse an array using STL functions in C++. So if the array is like A = [10, 20, 30, 40, 50, 60], then the output will be B = [60, 50, 40, 30, 20, 10]. To reverse we have one function called reverse() present in the header file <algorithm>. The code is like below −

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
   int arr[] = {10, 20, 30, 40, 50, 60};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Array before reverse: ";
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
   reverse(arr, arr + n);
   cout << "\nArray after reverse: ";
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
}

Output

Array before reverse: 10 20 30 40 50 60
Array after reverse: 60 50 40 30 20 10
raja
Published on 17-Dec-2019 17:45:07
Advertisements