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


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

Updated on: 17-Dec-2019

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements