Open In App

How to Reverse a Vector using STL in C++?

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

Reversing the vector means the swapping last element and first element, second last element and second element, and so on. In this article, we will learn how to reverse a vector using STL in C++.

The most efficient method to reverse the vector is by using reverse() function. Let’s take a look at a simple example:

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

int main() {
    vector<int> v = {1, 3, 5, 7, 9};

    // Reverse the vector
    reverse(v.begin(), v.end());

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

Output
9 7 5 3 1 

Explanation: The reverse() function reversed the order of all elements of the vector v.

C++ also provides other methods to reverse a vector. Some of them are as follows:

Using Reverse Iterators

Create a temporary reversed vector using the reverse iterators vector rbegin() and vector rend() and range constructor. Then copy back this temporary vector to the original vector.

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

int main() {
    vector<int> v = {1, 3, 5, 7, 9};

    // Reversing the vector
    v = vector<int>(v.rbegin(), v.rend());

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

Output
9 7 5 3 1 

Using reverse_copy()

The reverse_copy() function copies the elements from the original vector in reverse order into a new vector, leaving the original vector unchanged.

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

int main() {
    vector<int> v = {1, 3, 5, 7, 9};
    vector<int> temp(v.size());

    // Reverse copying the vector into temp vector
    reverse_copy(v.begin(), v.end(), temp.begin());

    // Copying back reversed vector
    v = temp;

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

Output
9 7 5 3 1 

Using Stack

Move all elements of vector into stack container leaving the stack empty. Then insert elements from the stack in the vector one by one.

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

int main() {
    vector<int> v = {1, 3, 5, 7, 9};
    stack<int> s;

    // Push all elements of vector into stack
    for (auto i : v)
        s.push(i);
    v.clear();

    // Push all elements of stack back into vector
    while (!s.empty()) {
        v.push_back(s.top());
        s.pop();
    }
    for (auto i : v)
        cout << i << " ";
  
    return 0;
}

Output
9 7 5 3 1 


Next Article
Article Tags :
Practice Tags :

Similar Reads