std::reverse
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class BidirIt > void reverse( BidirIt first, BidirIt last ); |
(1) | (C++20 起為 constexpr) |
template< class ExecutionPolicy, class BidirIt > void reverse( ExecutionPolicy&& policy, BidirIt first, BidirIt last ); |
(2) | (C++17 起) |
1) 將範圍
[
first,
last)
中的元素順序反轉。 其行為等同於對每個整數 i 在
[
0,
std::distance(first, last) / 2)
範圍內,將迭代器對 first + i 和 (last - i) - 1 應用 std::iter_swap。2) 同 (1),但根據 policy 執行。
僅當滿足以下所有條件時,此過載才參與過載決議
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 為 true。 |
(C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 為 true。 |
(C++20 起) |
如果 *first 不可交換 (Swappable)(C++20 前)BidirIt
不可值交換 (ValueSwappable)(C++20 起),則行為未定義。
目錄 |
[編輯] 引數
first, last | - | 定義要反轉的元素範圍的迭代器對 |
policy | - | 要使用的 執行策略 |
型別要求 | ||
-BidirIt 必須滿足舊式雙向迭代器 (LegacyBidirectionalIterator) 的要求。 |
[編輯] 複雜度
精確地 std::distance(first, last) / 2 次交換。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 若作為演算法一部分呼叫的函式丟擲異常,且
ExecutionPolicy
為標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為由實現定義。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能的實現
另見 libstdc++、libc++ 和 MSVC STL 中的實現。
template<class BidirIt> constexpr // since C++20 void reverse(BidirIt first, BidirIt last) { using iter_cat = typename std::iterator_traits<BidirIt>::iterator_category; // Tag dispatch, e.g. calling reverse_impl(first, last, iter_cat()), // can be used in C++14 and earlier modes. if constexpr (std::is_base_of_v<std::random_access_iterator_tag, iter_cat>) { if (first == last) return; for (--last; first < last; (void)++first, --last) std::iter_swap(first, last); } else while (first != last && first != --last) std::iter_swap(first++, last); } |
[編輯] 注意
當迭代器型別滿足舊式連續迭代器 (LegacyContiguousIterator) 且交換其值型別不呼叫非平凡特殊成員函式或 ADL 查詢的 swap
時,實現(例如 MSVC STL)可能會啟用向量化。
[編輯] 示例
執行此程式碼
#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); }
輸出
after reverse, v = 3 2 1 after reverse, a = 7 6 5 4
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 223 | C++98 | std::swap 應用於每對迭代器 | 轉為應用 std::iter_swap |
LWG 2039 | C++98 | 當 i 等於 std::distance(first, last) / 2 時,也會應用 std::iter_swap 等於 std::distance(first, last) / 2 |
不應用 |
[編輯] 參閱
建立一個反轉後的範圍副本 (函式模板) | |
(C++20) |
反轉一個範圍中元素的順序 (演算法函式物件) |