std::reverse

Header: <algorithm>

  1. Reverses the order of the elements in the range [first,last).

# Declarations

template< class BidirIt >
void reverse( BidirIt first, BidirIt last );

(constexpr since C++20)

template< class ExecutionPolicy, class BidirIt >
void reverse( ExecutionPolicy&& policy, BidirIt first, BidirIt last );

(since C++17)

# Parameters

# Notes

Implementations (e.g. MSVC STL) may enable vectorization when the iterator type satisfies LegacyContiguousIterator and swapping its value type calls neither non-trivial special member function nor ADL-found swap.

# Example

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
 
void println(auto rem, auto const& v)
{
    for (std::cout << rem; auto e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}
 
int main()
{
    std::vector<int> v {1, 2, 3};
    std::reverse(v.begin(), v.end());
    println("after reverse, v = ", v);
 
    int a[] = {4, 5, 6, 7};
    std::reverse(std::begin(a), std::end(a));
    println("after reverse, a = ", a);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 223C++98std::swap was applied to each pair of iteratorsapplies std::iter_swap instead
LWG 2039C++98std::iter_swap was also applied when iequals std::distance(first, last) / 2not applied

# See also