std::reverse_copy
来自 cppreference.cn
定义于头文件 <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 起) |
1) 给定 N 为 std::distance(first, last)。将范围
[
first,
last)
(源范围)中的元素复制到从 d_first 开始的另一个 N 个元素的范围(目标范围),使得目标范围中的元素按逆序排列。 如果源范围和目标范围重叠,则行为是未定义的。
2) 同 (1),但根据 policy 执行。
仅当满足以下所有条件时,此重载才参与重载决议
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 起) |
目录 |
[edit] 参数
first, last | - | 定义要复制的元素的源 范围 的迭代器对 |
d_first | - | 目标范围的开头 |
类型要求 | ||
-BidirIt 必须满足 LegacyBidirectionalIterator 的要求。 | ||
-OutputIt 必须满足 LegacyOutputIterator 的要求。 | ||
-ForwardIt 必须满足 LegacyForwardIterator 的要求。 |
[edit] 返回值
指向复制的最后一个元素之后一个元素的输出迭代器。
[edit] 复杂度
精确 N 次赋值。
[edit] 异常
带有名为 ExecutionPolicy
的模板参数的重载会按如下方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用 std::terminate。对于任何其他ExecutionPolicy
,行为是实现定义的。 - 如果算法未能分配内存,则抛出 std::bad_alloc。
[edit] 可能的实现
另请参见 libstdc++、libc++ 和 MSVC STL 中的实现。
template<class BidirIt, class OutputIt> constexpr // since C++20 OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first) { for (; first != last; ++d_first) *d_first = *(--last); return d_first; } |
[edit] 注意
当两个迭代器类型都满足 LegacyContiguousIterator 并具有相同的值类型,并且值类型为 TriviallyCopyable 时,实现(例如 MSVC STL)可能会启用向量化。
[edit] 示例
运行此代码
#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
[edit] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 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 不要求支持二元
+
和-
。这里使用+
和-
仅用于说明:实际计算不需要使用它们。
[edit] 参阅
反转一个范围中元素的顺序 (函数模板) | |
(C++20) |
创建一个反转后的范围副本 (算法函数对象) |