Logo
Section 1 / 11

复制元素和范围

在本节课中,我们将学习如何对指定范围执行各种复制操作。

导入

复制元素和范围

在本节课中,我们将学习如何对指定范围执行各种复制操作。

我们可以使用 std::copy 向前复制范围,使用 std::copy_backward 向后复制范围,使用 std::copy_if 条件性地复制元素。要复制 n 个元素,可以使用 std::copy_n。

copy:复制指定范围的元素。

1OutIt copy(InpIt first, InpIt last, OutIt result) 2FwdIt2 copy(ExePol pol, FwdIt first, FwdIt last, FwdIt2 result)

copy_n:复制 n 个元素。

1OutIt copy_n(InpIt first, Size n, OutIt result) 2FwdIt2 copy_n(ExePol pol, FwdIt first, Size n, FwdIt2 result)

copy_if:根据谓词 pre 的条件复制元素。

1OutIt copy_if(InpIt first, InpIt last, OutIt result, UnPre pre) 2FwdIt2 copy_if(ExePol pol, FwdIt first, FwdIt last, FwdIt2 result, UnPre pre)

copy_backward:向后复制范围。

1BiIt copy_backward(BiIt first, BiIt last, BiIt result)

这些算法需要输出迭代器来接收被复制的元素。copy、copy_n 和 copy_if 返回指向目标范围末尾(最后一个被复制元素之后)的迭代器,copy_backward 则返回指向目标范围起始位置(第一个被复制元素)的迭代器。

1#include <algorithm> 2#include <iostream> 3#include <string> 4#include <vector> 5 6int main(){ 7 8 std::cout << std::endl; 9 10 std::vector<int> myVec{0, 1, 2, 3, 4, 5, 6, 7, 9}; 11 std::vector<int> myVec2(10); 12 13 std::copy_if(myVec.begin(), myVec.end(), myVec2.begin()+3, [](int a){ return a%2; }); 14 for ( auto v: myVec2 ) std::cout << v << " "; 15 16 std::cout << "\n\n"; 17 18 std::string str{"Iamstring1"}; 19 std::string str2{"Hellostring---------------------2"}; 20 21 std::cout << str2 << std::endl; 22 std::copy_backward(str.begin(), str.end(), str2.end()); 23 std::cout << str2 << std::endl; 24 25 std::cout << std::endl; 26 27 std::cout << str << std::endl; 28 std::copy_backward(str.begin(), str.begin() + 5, str.end()); 29 std::cout << str << std::endl; 30 31 std::cout << std::endl; 32 33}

接下来的课程中,我们将学习用于更新和替换范围中值的函数。

1.1 非修改性算法

替换元素和范围