命名空间
变体
操作

std::copy, std::copy_if

来自 cppreference.cn
< 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)
将一定数量的元素复制到一个新位置
(函数模板) [编辑]
将给定值复制赋给一个范围中的每个元素
(函数模板) [编辑]
复制一个范围的元素,忽略那些满足特定条件的元素
(函数模板) [编辑]
将一个范围的元素复制到一个新位置
(算法函数对象)[编辑]