To reverse a vector in C++, you can use the `std::reverse` function.
In this example,
intVector
containing integers.std::reverse
function to reverse the order of elements in the vector.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> intVector = {1, 2, 3, 4, 5};
std::reverse(intVector.begin(), intVector.end());
for (const auto& num : intVector) {
std::cout << num << " ";
}
return 0;
}
5 4 3 2 1
In this example,
charVector
containing characters.std::reverse
function to reverse the order of elements in the vector.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<char> charVector = {'a', 'b', 'c', 'd', 'e'};
std::reverse(charVector.begin(), charVector.end());
for (const auto& ch : charVector) {
std::cout << ch << " ";
}
return 0;
}
e d c b a
In this tutorial, we learned How to Reverse a Vector in C++ language with well detailed examples.