In this C++ tutorial, you shall learn how to reverse a vector using std::reverse() function, with example programs.

Reverse a Vector

To reverse a vector in C++, we can use std::reverse() method of algorithm library.

Import algorithm library, call sort() method, and pass the beginning and ending of the vector as arguments to the method. The method sorts the vector in-place, i.e., the original vector is updated.

The syntax of the statement to reverse a vector v is

//include algorithm
#include <algorithm>

//call reverse method
std::reverse(v.begin(), v.end());

C++ Program

In the following program, we take a vector of strings in v, and reverse it using reverse() method.

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
   vector<string> v { "apple", "banana", "cherry" };
   
   reverse(v.begin(), v.end());

   for(auto& element: v) {
      cout << element << "  ";
   }
}

Output

cherry  banana  apple
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to reverse a vector using std::reverse() method of algorithm library.