This post will discuss how to reverse a vector in C++.

Practice this problem

1. Using std::reverse function

The simplest solution is to use the std::reverse function defined in the <algorithm> header. This function internally uses std::iter_swap for swapping the elements from both ends of the given range.

Download  Run Code

Output:

Original Vector: 1 2 3 4 5
Reversed Vector: 5 4 3 2 1

2. Using Reverse Iterators

Here, the idea is to use reverse iterators to construct a new vector using its range constructor. Then we can simply swap the original vector with the new vector.

Download  Run Code

3. Using std::swap function

We have seen that std::reverse function internally uses std::iter_swap function. The same can be achieved with the help of the std::swap function, as shown below:

Download  Run Code

4. Using std::transform function

Finally, another good solution is to use the std::transform algorithm, as shown below:

Download  Run Code

That’s all about reversing a vector in C++.