std:: reverse_copy
|
定义于头文件
<algorithm>
|
||
|
template
<
class
BidirIt,
class
OutputIt
>
OutputIt reverse_copy
(
BidirIt first, BidirIt last,
|
(1) | (自 C++20 起为 constexpr) |
|
template
<
class
ExecutionPolicy,
class
BidirIt,
class
ForwardIt
>
ForwardIt reverse_copy
(
ExecutionPolicy
&&
policy,
|
(2) | (自 C++17 起) |
[
first
,
last
)
(源范围)复制到始于
d_first
的另一个包含
N
个元素的范围(目标范围),使得目标范围中的元素呈逆序排列。
|
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 | - | 目标范围的起始位置 |
| 类型要求 | ||
-
BidirIt
必须满足
LegacyBidirectionalIterator
的要求。
|
||
-
OutputIt
必须满足
LegacyOutputIterator
的要求。
|
||
-
ForwardIt
必须满足
LegacyForwardIterator
的要求。
|
||
返回值
指向最后一个被复制元素之后位置的输出迭代器。
复杂度
恰好有 N 个任务。
异常
带有名为
ExecutionPolicy
模板参数的重载按以下方式报告错误:
-
如果作为算法一部分调用的函数执行抛出异常,且
ExecutionPolicy是某个 标准策略 ,则调用 std::terminate 。对于其他任何ExecutionPolicy,其行为由实现定义。 - 如果算法无法分配内存,则抛出 std::bad_alloc 。
可能的实现
另请参阅 libstdc++ 、 libc++ 和 MSVC STL 中的实现。
template<class BidirIt, class OutputIt> constexpr // 自 C++20 起 OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first) { for (; first != last; ++d_first) *d_first = *(--last); return d_first; } |
注释
实现(例如 MSVC STL )可在满足以下条件时启用向量化:两个迭代器类型均符合 LegacyContiguousIterator 且具有相同值类型,同时该值类型为 TriviallyCopyable 。
示例
#include <algorithm> #include <iostream> #include <vector> int main() { auto print = [](const std::vector<int>& v) { for (const auto& value : v) std::cout << value << ' '; std::cout << '\n'; }; std::vector<int> v{1, 2, 3}; print(v); std::vector<int> destination(3); std::reverse_copy(std::begin(v), std::end(v), std::begin(destination)); print(destination); std::reverse_copy(std::rbegin(v), std::rend(v), std::begin(destination)); print(destination); }
输出:
1 2 3 3 2 1 1 2 3
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 适用范围 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 2074 | C++98 |
对每个
i
,赋值操作为
* ( d_first + N - i ) = * ( first + i ) [1] |
修正为
* ( d_first + N - 1 - i ) = * ( first + i ) [1] |
| LWG 2150 | C++98 | 仅要求赋值一个元素 | 修正了该要求 |
-
↑
1.0
1.1
1.2
LegacyOutputIterator
不要求支持二元运算符
+和-。此处对+和-的使用仅为示意说明:实际计算无需使用这些运算符。
参见
|
反转范围中元素的顺序
(函数模板) |
|
|
(C++20)
|
创建反转后的范围副本
(算法函数对象) |