std::reverse_copy
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
template< class BidirIt, class OutputIt > OutputIt reverse_copy( BidirIt first, BidirIt last, |
(1) | (C++20 起為 constexpr) |
template< class ExecutionPolicy, class BidirIt, class ForwardIt > ForwardIt reverse_copy( ExecutionPolicy&& policy, |
(2) | (C++17 起) |
1) 給定 N 為 std::distance(first, last)。將範圍
[
first,
last)
(源範圍)中的元素複製到從 d_first 開始的另一個 N 個元素的範圍(目標範圍),使得目標範圍中的元素按逆序排列。 如果源範圍和目標範圍重疊,則行為是未定義的。
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 起) |
目錄 |
[edit] 引數
first, last | - | 定義要複製的元素的源 範圍 的迭代器對 |
d_first | - | 目標範圍的開頭 |
型別要求 | ||
-BidirIt 必須滿足 LegacyBidirectionalIterator 的要求。 | ||
-OutputIt 必須滿足 LegacyOutputIterator 的要求。 | ||
-ForwardIt 必須滿足 LegacyForwardIterator 的要求。 |
[edit] 返回值
指向複製的最後一個元素之後一個元素的輸出迭代器。
[edit] 複雜度
精確 N 次賦值。
[edit] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式的執行丟擲異常,並且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[edit] 可能的實現
另請參見 libstdc++、libc++ 和 MSVC STL 中的實現。
template<class BidirIt, class OutputIt> constexpr // since C++20 OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first) { for (; first != last; ++d_first) *d_first = *(--last); return d_first; } |
[edit] 注意
當兩個迭代器型別都滿足 LegacyContiguousIterator 並具有相同的值型別,並且值型別為 TriviallyCopyable 時,實現(例如 MSVC STL)可能會啟用向量化。
[edit] 示例
執行此程式碼
#include <algorithm> #include <iostream> #include <vector> int main() { auto print = [](const std::vector<int>& v) { for (const auto& value : v) std::cout << value << ' '; std::cout << '\n'; }; std::vector<int> v{1, 2, 3}; print(v); std::vector<int> destination(3); std::reverse_copy(std::begin(v), std::end(v), std::begin(destination)); print(destination); std::reverse_copy(std::rbegin(v), std::rend(v), std::begin(destination)); print(destination); }
輸出
1 2 3 3 2 1 1 2 3
[edit] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2074 | C++98 | 對於每個 i,賦值為 *(d_first + N - i) = *(first + i)[1] |
更正為 *(d_first + N - 1 - i) = *(first + i)[1] |
LWG 2150 | C++98 | 只需要賦值一個元素 | 修正了要求 |
- ↑ 1.0 1.1 1.2 LegacyOutputIterator 不要求支援二元
+
和-
。這裡使用+
和-
僅用於說明:實際計算不需要使用它們。
[edit] 參閱
反轉一個範圍中元素的順序 (函式模板) | |
(C++20) |
建立一個反轉後的範圍副本 (演算法函式物件) |