This post will discuss how to reverse the contents of an array in C++.

1. Using std::reverse

A simple solution to in-place reverse contents of an array is using the std::reverse algorithm from the standard library. The reverse algorithm is defined in the <algorithm> header and can be used as follows:

Download  Run Code

Output:

5 4 3 2 1

2. Using std::swap

Another alternative is to use the std::swap algorithm defined in the <algorithm> header. It works by swapping the values of objects pointed to by specified iterators. A typical invocation for the std::swap algorithm would look like below, to reverse an array:

Download  Run Code

Output:

5 4 3 2 1

 
We can even write a custom routine for the swapping task. It can be implemented as follows to reverse an array:

Download  Run Code

Output:

5 4 3 2 1

That’s all about reversing the contents of an array in C++.