What is the std::reverse() function in C++?

std::reverse() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and reverses the order of the element in the given range.

Take a look at the function signature of std::reverse() below:

Function signature of std::reverse()

Code

Using std::reverse with a std::vector

#include <vector>
#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
using namespace std;
int main() {
std::vector<int> values = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::cout << "Before reversing: ";
for(int x: values) {
std::cout << x << ' ';
}
std::reverse(values.begin(), values.end());
std::cout << "\nAfter reversing: ";
for(int x: values) {
std::cout << x << ' ';
}
}

Using std::reverse with a std::string

#include <string>
#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
using namespace std;
int main() {
std::string sentence = "Hello, World!";
std::cout << "Before reversing: " << sentence << '\n';
std::reverse(sentence.begin(), sentence.end());
std::cout << "After reversing: " << sentence << '\n';
}

Using std::reverse with a built-in array type

#include <iostream>
// The following header needs to be included to use std::reverse()
#include <algorithm>
// The following header needs to be included to use std::begin() and std::end()
#include <iterator>
using namespace std;
int main() {
int arr[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
std::cout << "Before reversing: ";
for(int x: arr) {
std::cout << x << ' ';
}
// built-in array has no begin() and end() member functions
// but we can pass it to std::begin() and std::end()
// in order to get the iterators we need
std::reverse(std::begin(arr), std::end(arr));
std::cout << "\nAfter reversing: ";
for(int x: arr) {
std::cout << x << ' ';
}
}

Free Resources