名稱空間
變體
操作

std::reverse_copy

來自 cppreference.com
< cpp‎ | 演算法
 
 
演算法庫
有約束演算法與針對範圍的演算法 (C++20)
有約束的演算法,例如 ranges::copyranges::sort 等……
執行策略 (C++17)
排序及相關操作
劃分操作
排序操作
二分搜尋操作
(於已劃分範圍上)
集合操作(於已排序範圍上)
歸併操作(於已排序範圍上)
堆操作
最小/最大值操作
(C++11)
(C++17)
字典序比較操作
排列操作
C 庫
數值操作
未初始化記憶體上的操作
 
定義於標頭檔案 <algorithm>
template< class BidirIt, class OutputIt >

OutputIt reverse_copy( BidirIt first, BidirIt last,

                       OutputIt d_first );
(1) (C++20 起為 constexpr)
template< class ExecutionPolicy, class BidirIt, class ForwardIt >

ForwardIt reverse_copy( ExecutionPolicy&& policy,
                        BidirIt first, BidirIt last,

                        ForwardIt d_first );
(2) (C++17 起)
1) 給定 Nstd::distance(first, last)。將範圍 [firstlast) (源範圍)中的元素複製到從 d_first 開始的另一個 N 個元素的範圍(目標範圍),使得目標範圍中的元素按逆序排列。
行為如同透過為 0N(不含 N)中的每個整數 i 執行一次賦值 *(d_first + N - 1 - i) = *(first + i)[1]
如果源範圍和目標範圍重疊,則行為是未定義的。
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. 1.0 1.1 1.2 LegacyOutputIterator 不要求支援二元 +-。這裡使用 +- 僅用於說明:實際計算不需要使用它們。

[edit] 參閱

反轉一個範圍中元素的順序
(函式模板) [編輯]
建立一個反轉後的範圍副本
(演算法函式物件)[編輯]