To reverse the order of elements in a vector using the C++ standard library, you can utilize the std::reverse()
algorithm from the <algorithm>
 header.
This algorithm works with iterators and allows you to reverse the elements of any container that provides iterator access, such as std::vector
.
Here’s an example demonstrating how to reverse a vector of integers:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> numbers {1, 2, 3, 4, 5};
// Reversing the vector
std::reverse(numbers.begin(), numbers.end());
// Printing the reversed vector
for (const int& num : numbers) {
std::cout << num << " ";
}
}
5 4 3 2 1
<algorithm>
header to access the std::reverse()
function.std::reverse()
function takes two iterators: the beginning and the end of the range you want to reverse. By passing numbers.begin()
and numbers.end()
, you reverse the entire vector.Reversing a vector can be useful in various scenarios, such as:
std::reverse(numbers.begin() + 1, numbers.begin() + 4);
.std::reverse()
algorithm works with any container that supports bidirectional iterators, not just std::vector
.Reversing a vector is a simple yet powerful operation that can be easily achieved using the C++ standard library, making your code more versatile and efficient.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterator and range-based algorithms, using examples from the standard library