To reverse an array in C++, you can use the standard library function std::reverse from the
In this example,
intArray
containing integers.
header to use the std::reverse
function.std::reverse
on the range of elements in intArray
to reverse the array.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> intArray = {1, 2, 3, 4, 5};
std::reverse(intArray.begin(), intArray.end());
std::cout << "Reversed Array: ";
for (int num : intArray) {
std::cout << num << " ";
}
return 0;
}
Reversed Array: 5 4 3 2 1
In this example,
strArray
containing strings.
header to use the std::reverse
function.std::reverse
on the range of elements in strArray
to reverse the array.#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strArray = {"apple", "banana", "cherry"};
std::reverse(strArray.begin(), strArray.end());
std::cout << "Reversed Array: ";
for (const std::string& str : strArray) {
std::cout << str << " ";
}
return 0;
}
Reversed Array: cherry banana apple
In this tutorial, we learned How to Reverse an Array in C++ language with well detailed examples.