Defined in header <algorithm> | ||
---|---|---|
Call signature | ||
template< std::bidirectional_iterator I, std::sentinel_for<I> S > requires std::permutable<I> constexpr I reverse( I first, S last ); | (1) | (since C++20) |
template< ranges::bidirectional_range R > requires std::permutable<ranges::iterator_t<R>> constexpr ranges::borrowed_iterator_t<R> reverse( R&& r ); | (2) | (since C++20) |
[
first
,
last
)
.ranges::iter_swap
to every pair of iterators first + i, last - i - 1
for each integer i
, where 0 ≤ i < (last - first) / 2
.r
as the range, as if using ranges::begin(r)
as first
and ranges::end(r)
as last
.The function-like entities described on this page are niebloids, that is:
In practice, they may be implemented as function objects, or with special compiler extensions.
first, last | - | the range of elements to reverse |
r | - | the range of elements to reverse |
An iterator equal to last
.
Exactly (last - first) / 2
swaps.
Implementations (e.g. MSVC STL) may enable vectorization when the iterator type models contiguous_iterator
and swapping its value type calls neither non-trivial special member function nor ADL-found swap
.
See also implementations in libstdc++ and MSVC STL.
#include <algorithm> #include <array> #include <iostream> #include <string> int main() { std::string s {"ABCDEF"}; std::cout << s << " → "; std::ranges::reverse(s.begin(), s.end()); std::cout << s << " → "; std::ranges::reverse(s); std::cout << s << " │ "; std::array a {1, 2, 3, 4, 5}; for (auto e : a) std::cout << e << ' '; std::cout << "→ "; std::ranges::reverse(a); for (auto e : a) std::cout << e << ' '; std::cout << '\n'; }
Output:
(C++20) | creates a copy of a range that is reversed (niebloid) |
(C++20) | a view that iterates over the elements of another bidirectional view in reverse order (class template) (range adaptor object) |
reverses the order of elements in a range (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/algorithm/ranges/reverse