Open In App

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

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Reversing an array means rearranging its elements so that the first element becomes the last, the second element becomes the second last, and so on. In this article, we will learn how to reverse an array using STL in C++.

The most efficient way to reverse an array using STL is by using reverse() function. Let’s take a look at a simple example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {1, 3, 4, 7};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Reverse the array arr
    reverse(arr, arr + n);

    for (auto i : arr)
        cout << i << " ";
    return 0;
}

Output
7 4 3 1 

This method reverses the array in-place i.e. it modifies the original array and rearranges it in reverse order.

Apart from the reverse() function, STL also provides some other methods to reverse an array. Some of them are as follows:

Using reverse_copy()

The reverse_copy() function can also be used to reverse an array. It is similar to the reverse() function but it does not modify the original array, instead it stores the reversed version in a separate array.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {1, 3, 4, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    int rev[n];

    // Reverse the array arr
    reverse_copy(arr, arr + n, rev);

    for (auto i : rev)
        cout << i << " ";
    return 0;
}

Output
7 4 3 1 

Using Reverse Iterators

Though array doesn’t have inbuilt reverse iterators, they can be created using rbegin() and rend() function. Then copy() function can be used to copy the elements in the reverse order in some separate array.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[] = {1, 3, 4, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    int rev[n];

    // Copy all elements into another array 
    // in reversed order
    copy(rbegin(arr), rend(arr), rev);

    for (auto i : rev)
        cout << i << " ";
    return 0;
}

Output
7 4 3 1 


Next Article
Practice Tags :

Similar Reads