A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/how-to-reverse-a-vector-using-stl-in-c/ below:

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

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

Last Updated : 11 Jul, 2025

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;
}

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;
}
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;
}
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;
}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4