How to Use reverse in C++: Syntax and Examples
In C++, you can use the
std::reverse function from the <algorithm> header to reverse elements in a container like an array or vector. Call it with two iterators marking the start and end of the range you want to reverse, for example, std::reverse(vec.begin(), vec.end()).Syntax
The std::reverse function reverses the order of elements in a range defined by two iterators.
first: Iterator to the beginning of the range.last: Iterator to one past the end of the range.
It modifies the container in place.
cpp
std::reverse(first, last);
Example
This example shows how to reverse a vector of integers using std::reverse. It prints the vector before and after reversing.
cpp
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; std::cout << "Before reverse: "; for (int n : numbers) std::cout << n << ' '; std::cout << '\n'; std::reverse(numbers.begin(), numbers.end()); std::cout << "After reverse: "; for (int n : numbers) std::cout << n << ' '; std::cout << '\n'; return 0; }
Output
Before reverse: 1 2 3 4 5
After reverse: 5 4 3 2 1
Common Pitfalls
Common mistakes when using std::reverse include:
- Passing invalid or reversed iterators (the first iterator must come before the last).
- Trying to reverse a container without including
<algorithm>. - Expecting
std::reverseto return a new container; it modifies in place and returns void.
cpp
#include <vector> #include <algorithm> // Wrong: reversed iterators // std::reverse(vec.end(), vec.begin()); // This causes undefined behavior // Correct: // std::reverse(vec.begin(), vec.end());
Quick Reference
- Include
<algorithm>to usestd::reverse. - Use iterators to specify the range to reverse.
- Works with arrays, vectors, strings, and other containers supporting iterators.
- Modifies the container in place; no return value.
Key Takeaways
Use std::reverse from to reverse elements between two iterators.
Always pass the beginning iterator first, then the end iterator (one past last element).
std::reverse modifies the container in place and returns void.
Works with many containers like vectors, arrays, and strings.
Include header to access std::reverse.