C++ Reverse Function: Usage & Examples
The reverse function in C++ is used to reverse the order of elements in a container. It can be used to reverse arrays, vectors, lists, strings, and other containers.
The usage of the reverse function is as follows:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::reverse(vec.begin(), vec.end());
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
The output is: 5 4 3 2 1
The reverse function takes two iterators as parameters, representing the starting and ending positions of a container. It reverses the elements in the container by swapping the first element with the last element, the second element with the second last element, and so on.
It should be noted that the reverse function can only be used for sequential containers, not for associative containers (such as sets, maps) and unordered containers (such as hash tables).