C++ std::reverse() Function

Definition
In C++, std::reverse() flips a range so the first element becomes the last and the last becomes the first. The change happens in place.
It works on vectors, strings, arrays and any container that supports bidirectional iterators.
Syntax
Add #include <algorithm>, then call std::reverse(). Start with these two lines.
std::reverse(v.begin(), v.end());
std::reverse(v.begin() + 1, v.begin() + 5);
| Call | What it does |
|---|
std::reverse(v.begin(), v.end()); | Reverse the whole container. |
std::reverse(v.begin() + 1, v.begin() + 5); | Reverse only part of it. |
Library declarations
template<class BidirIt>
void reverse(BidirIt first, BidirIt last);
Parameters
| Parameter | Description |
|---|
| first, last | Required. The range to reverse. |
Return Value
| Return Value | Description |
|---|
void | Nothing is returned. The range is changed in place. |
C++ Examples
Example 1 — Reverse a vector
Flip five numbers.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
std::reverse(v.begin(), v.end());
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
How It Works
- The call swaps the first and last elements, then the second and second-to-last.
- The middle element stays where it is.
- The vector now reads from 5 down to 1.
Example 2 — Reverse a string
Flip the letters of a word.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string word = "CodeToFun";
std::reverse(word.begin(), word.end());
std::cout << word << '\n';
return 0;
}
How It Works
- A string is a range of characters, so it can be reversed like a vector.
- The first letter
C swaps with the last letter n, and so on. - Capital letters move with their characters.
Example 3 — Reverse part of a vector
Flip only the middle of a vector.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
std::reverse(v.begin() + 1, v.begin() + 5);
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
How It Works
- The range starts at index 1 and stops before index 5.
- Only 2, 3, 4 and 5 are flipped.
- The first element 1 and the last element 6 stay in place.
Frequently Asked Questions
In C++, std::reverse() reverses the order of the elements in a range. Include <algorithm> to use it.
Include <algorithm>. It has been part of C++ since C++98, so every modern compiler supports it.
It returns nothing (void). The elements in the range are reversed in place.
Call std::reverse(s.begin(), s.end()). It changes the string in place.
Use std::reverse_copy() and write the result to another container.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
7 people found this page helpful