名稱空間
變體
操作

std::copy, std::copy_if

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

OutputIt copy( InputIt first, InputIt last,

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

          class ForwardIt1, class ForwardIt2 >
ForwardIt2 copy( ExecutionPolicy&& policy,
                 ForwardIt1 first, ForwardIt1 last,

                 ForwardIt2 d_first );
(2) (C++17 起)
template< class InputIt, class OutputIt, class UnaryPred >

OutputIt copy_if( InputIt first, InputIt last,

                  OutputIt d_first, UnaryPred pred );
(3) (C++11 起)
(C++20 起為 constexpr)
template< class ExecutionPolicy,

          class ForwardIt1, class ForwardIt2, class UnaryPred >
ForwardIt2 copy_if( ExecutionPolicy&& policy,
                    ForwardIt1 first, ForwardIt1 last,

                    ForwardIt2 d_first, UnaryPred pred );
(4) (C++17 起)

將由 [firstlast) 定義的範圍中的元素複製到從 d_first 開始的另一個範圍(複製目標範圍)。

1) 複製範圍 [firstlast) 中的所有元素,從 first 開始並進行到 last
如果 d_first[firstlast) 中,則行為未定義。在這種情況下,可以使用 std::copy_backward 代替。
2) 複製元素,但根據 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 起)
如果 [firstlast) 和複製目標範圍重疊,則行為未定義。
3) 僅複製謂詞 pred 返回 true 的元素。此複製演算法是穩定的:複製的元素的相對順序得以保留。
如果 [firstlast) 和複製目標範圍重疊,則行為未定義。
4)(3) 相同,但根據 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, last - 定義要複製的元素的源 範圍 的迭代器對
d_first - 目標範圍的開頭
policy - 要使用的 執行策略
pred - 一元謂詞,對於所需元素返回 ​true

對於型別為 (可能為 const) VT 的每個引數 v,表示式 pred(v) 必須可轉換為 bool,無論 值類別 如何,並且不得修改 v。因此,不允許引數型別為 VT&,除非對於 VT 移動等同於複製,否則也不允許 VT(C++11 起)。​

型別要求
-
InputIt 必須滿足 LegacyInputIterator 的要求。
-
OutputIt 必須滿足 LegacyOutputIterator 的要求。
-
ForwardIt1, ForwardIt2 必須滿足 LegacyForwardIterator 的要求。
-
UnaryPred 必須滿足 Predicate 的要求。

[編輯] 返回值

指向目標範圍中元素(複製的最後一個元素的後一個)的輸出迭代器。

[編輯] 複雜度

給定 Nstd::distance(first, last)

1,2) 恰好 N 次賦值。
3,4) 恰好 N 次謂詞 pred 的應用,以及至多 N 次賦值。

對於帶有 ExecutionPolicy 的過載,如果 ForwardIt1 的值型別不是 MoveConstructible,則可能會有效能開銷。

[編輯] 異常

帶有模板引數 ExecutionPolicy 的過載按如下方式報告錯誤

  • 如果作為演算法一部分呼叫的函式執行丟擲異常,並且 ExecutionPolicy標準策略 之一,則呼叫 std::terminate。對於任何其他 ExecutionPolicy,行為是實現定義的。
  • 如果演算法未能分配記憶體,則丟擲 std::bad_alloc

[編輯] 可能的實現

copy (1)
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,
              OutputIt d_first)
{
    for (; first != last; (void)++first, (void)++d_first)
        *d_first = *first;
 
    return d_first;
}
copy_if (3)
template<class InputIt, class OutputIt, class UnaryPred>
OutputIt copy_if(InputIt first, InputIt last,
                 OutputIt d_first, UnaryPred pred)
{
    for (; first != last; ++first)
        if (pred(*first))
        {
            *d_first = *first;
            ++d_first;
        }
 
    return d_first;
}

[編輯] 注意

在實踐中,如果值型別是 TriviallyCopyable 並且迭代器型別滿足 LegacyContiguousIteratorstd::copy 的實現會避免多次賦值並使用塊複製函式,例如 std::memmove

當複製重疊範圍時,當向左複製(目標範圍的開頭在源範圍之外)時,std::copy 是合適的,而當向右複製(目標範圍的末尾在源範圍之外)時,std::copy_backward 是合適的。

[編輯] 示例

以下程式碼使用 std::copy 複製一個 std::vector 的內容到另一個 std::vector,並顯示結果的 std::vector

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
 
int main()
{
    std::vector<int> from_vector(10);
    std::iota(from_vector.begin(), from_vector.end(), 0);    
    std::vector<int> to_vector;
    std::copy(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector));
 
// or, alternatively,
//  std::vector<int> to_vector(from_vector.size());
//  std::copy(from_vector.begin(), from_vector.end(), to_vector.begin());
// either way is equivalent to
//  std::vector<int> to_vector = from_vector;
 
    std::cout << "to_vector contains: ";
    std::copy(to_vector.begin(), to_vector.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
 
    std::cout << "odd numbers in to_vector are: ";
    std::copy_if(to_vector.begin(), to_vector.end(),
                 std::ostream_iterator<int>(std::cout, " "),
                 [](int x) { return x % 2 != 0; });
    std::cout << '\n';
 
    std::cout << "to_vector contains these multiples of 3: ";
    to_vector.clear();
    std::copy_if(from_vector.begin(), from_vector.end(),
                 std::back_inserter(to_vector),
                 [](int x) { return x % 3 == 0; });
 
    for (const int x : to_vector)
        std::cout << x << ' ';
    std::cout << '\n';
}

可能的輸出

to_vector contains: 0 1 2 3 4 5 6 7 8 9
odd numbers in to_vector are: 1 3 5 7 9
to_vector contains these multiples of 3: 0 3 6 9

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2039 C++11 std::copy_if 的返回值未指定 已指定
LWG 2044 C++11 std::copy_if 的穩定性未定義 已定義

[編輯] 另請參閱

以逆序複製一個範圍的元素
(函式模板) [編輯]
建立一個反轉後的範圍副本
(函式模板) [編輯]
(C++11)
將一定數量的元素複製到一個新位置
(函式模板) [編輯]
將給定值複製賦給一個範圍中的每個元素
(函式模板) [編輯]
複製一個範圍的元素,忽略那些滿足特定條件的元素
(函式模板) [編輯]
將一個範圍的元素複製到一個新位置
(演算法函式物件)[編輯]