Reverse contents of an array in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <algorithm> #include <iterator> int main() { int arr[] = {1, 2, 3, 4, 5}; std::reverse(std::begin(arr), std::end(arr)); for (int &i: arr) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <algorithm> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(*arr); for (int i = 0; i < n / 2; i++) { std::swap(arr[i], arr[n - i - 1]); } for (int &i: arr) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(*arr); for (int i = 0; i < n / 2; i++) { int temp = arr[n - i - 1]; arr[n - i - 1] = arr[i]; arr[i] = temp; } for (int &i: arr) { std::cout << i << ' '; } return 0; } |
Output:
5 4 3 2 1
That’s all about reversing the contents of an array in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)