导入
复制元素和范围
学习如何对指定范围执行各种复制操作。
可以使用 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, FowdIt2 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)
这些算法都需要输入迭代器,并将源范围内的元素复制到目标位置 result。函数执行后返回指向目标范围末尾的迭代器。
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}