C++ 标准库 - <algorithm>

C++ std::copy 把 [first, last) 依次写入以 d_first 起始的输出区间。算法本身不扩大容器,目标必须已有足够元素,或使用插入迭代器。

原型

template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last, OutputIt d_first);

参数

  • first, last:源区间。
  • d_first:目标起始迭代器。

返回值

指向目标中最后一个被写入元素的下一位置。

示例

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> a = {1, 2, 3};
    std::vector<int> b(3);
    std::copy(a.begin(), a.end(), b.begin());
    for (int x : b) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    return 0;
}

输出:

1 2 3 

注意事项

源与目标重叠时须改用 copy_backward 或先复制到临时区。向空 vector 追加可写 std::copy(..., std::back_inserter(b))。

下一页介绍transform:映射并写出结果。