std::copy_backward

来自cppreference.com
< cpp‎ | algorithm
 
 
算法库
受约束算法及范围上的算法(C++20)
包含算法例如 ranges::copy, ranges::sort, ...
执行策略 (C++17)
排序和相关操作
划分操作
排序操作
二分搜索操作(在已划分范围上)
集合操作(在有序范围上)
归并操作(在有序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库

数值运算
(C++11)                       
在未初始化内存上的操作
 
在标头 <algorithm> 定义
template<class BidirIt1, class BidirIt2 >
BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );
(C++20 起为 constexpr)

将范围 [firstlast) 内的元素复制到终于 d_last 的范围。以逆序复制元素(首先复制末元素),但保持相对顺序。

如果 d_last(firstlast] 中,那么行为未定义。此时必须用 std::copy 取代 std::copy_backward

目录

[编辑]参数

first, last - 要复制的源元素范围的迭代器对
d_last - 目标范围的结尾
类型要求
-
BidirIt 必须满足老式双向迭代器(LegacyBidirectionalIterator)

[编辑]返回值

指向最后复制元素的迭代器。

[编辑]复杂度

赋值 std::distance(first, last) 次。

[编辑]注意

复制重叠的范围时,在复制到左侧(目标范围的起始在源范围外)的情况下适合使用 std::copy,而在复制到右侧(目标范围的结尾在源范围外)的情况下适合使用 std::copy_backward

[编辑]可能的实现

template<class BidirIt1, class BidirIt2> BidirIt2 copy_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last){while(first != last)*(--d_last)=*(--last);return d_last;}

[编辑]示例

#include <algorithm>#include <iostream>#include <numeric>#include <vector>   int main(){std::vector<int> source(4);std::iota(source.begin(), source.end(), 1);// 填充 1, 2, 3, 4   std::vector<int> destination(6);   std::copy_backward(source.begin(), source.end(), destination.end());   std::cout<<"destination 包含:";for(auto i: destination)std::cout<< i <<' ';std::cout<<'\n';}

输出:

destination 包含:0 0 1 2 3 4

[编辑]缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 1206 C++98 1. d_last == last 时行为有良好定义
2. d_last == first 时行为未定义
1. 此时行为未定义
2. 此时行为有良好定义

[编辑]参阅

复制范围中元素到新位置
(函数模板)[编辑]
从后往前复制范围中元素
(算法函数对象)[编辑]
close