How to Reverse a Vector in C++: Simple Guide
To reverse a
std::vector in C++, use the std::reverse function from the <algorithm> header. Call it with iterators to the vector's beginning and end like std::reverse(vec.begin(), vec.end()) to reverse the elements in place.Syntax
The std::reverse function reverses the order of elements in a range defined by two iterators.
vec.begin(): Iterator to the first element of the vector.vec.end(): Iterator just past the last element of the vector.std::reverse: Function that swaps elements from start to end until the entire range is reversed.
cpp
std::reverse(vec.begin(), vec.end());
Example
This example shows how to reverse a vector of integers and print the result.
cpp
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::reverse(vec.begin(), vec.end()); for (int num : vec) { std::cout << num << ' '; } std::cout << '\n'; return 0; }
Output
5 4 3 2 1
Common Pitfalls
One common mistake is forgetting to include the <algorithm> header, which causes a compilation error. Another is reversing only part of the vector by using incorrect iterators, which results in only a section being reversed.
Also, trying to reverse a vector by copying elements manually is less efficient and more error-prone than using std::reverse.
cpp
#include <iostream> #include <vector> // Missing #include <algorithm> causes error int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; // std::reverse(vec.begin(), vec.end()); // Error if <algorithm> not included return 0; } // Correct way: #include <algorithm> // Must include this // std::reverse(vec.begin(), vec.end());
Quick Reference
- Include
<algorithm>to usestd::reverse. - Use
vec.begin()andvec.end()to reverse the whole vector. std::reversemodifies the vector in place.- Works with any container supporting random-access iterators.
Key Takeaways
Use std::reverse with vec.begin() and vec.end() to reverse a vector in place.
Always include header to access std::reverse.
std::reverse works efficiently and avoids manual element swapping.
Be careful to use correct iterators to reverse the intended range.
Reversing modifies the original vector; no new vector is created.