CKTIS / C++
std::reverse — reversing element order
std::reverse from <algorithm> reverses the elements of [first, last) in place. It requires bidirectional iterators and elements that can be swapped, and returns void.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::reverse(first, last);std::reverse(first, last) reverses the element order in a valid half-open range [first, last): first is included, while last points past the end. The function from <algorithm> modifies the elements in place and returns void.
The iterators must be at least bidirectional, and their elements must support swapping through std::iter_swap. Consequently, forward-only iterators and iterators to nonmodifiable elements cannot be used.
For N elements, the algorithm performs exactly N / 2 swaps using integer division: the first element with the last, the second with the next-to-last, and so on. Complexity is linear. Empty and single-element ranges remain unchanged. Reversing the order does not mean sorting in descending order.
The example reverses the entire array. To change only a subrange, pass that subrange's boundaries. Unlike std::reverse, std::reverse_copy writes a reversed copy into a separate, nonoverlapping range. The source is a living standard draft; this explanation is limited to behavior available in C++23.
Examples
#include <algorithm>
#include <iostream>
int main() {
int values[] = {1, 2, 3, 4, 5};
std::reverse(values, values + 5);
for (int i = 0; i < 5; ++i) {
if (i != 0) std::cout << ' ';
std::cout << values[i];
}
std::cout << '\n';
}
Result
5 4 3 2 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.