定义于头文件 <algorithm>
算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last)
,其中 last
指代要查询或修改的最后元素的后一个元素。
创建一个范围的逆向副本
std::reverse_copy
template< class BidirIt, class OutputIt > | (1) | (C++20 前) |
template< class BidirIt, class OutputIt > | (C++20 起) | |
template< class ExecutionPolicy, class BidirIt, class ForwardIt > | (2) | (C++17 起) |
1) 复制来自范围 [first, last)
的元素到始于 d_first
的新范围,使得新范围中元素以逆序排列。
表现如同通过对于每个非负的 i < (last - first)
执行一次赋值 *(d_first + (last - first) - 1 - i) = *(first + i) 。
若源与目标范围(分别为 [first, last)
和 [d_first, d_first+(last-first))
)重叠,则行为未定义。
2) 同 (1) ,但按照 policy
执行。此重载仅若 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true 才参与重载决议。
参数
first, last | - | 要复制的元素范围 |
d_first | - | 新范围的起始 |
类型要求 | ||
- BidirIt 必须满足遗留双向迭代器 (LegacyBidirectionalIterator) 的要求。 | ||
- OutputIt 必须满足遗留输出迭代器 (LegacyOutputIterator) 的要求。 | ||
- ForwardIt 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。 |
返回值
指向最后被复制元素后一元素的迭代器。
异常
拥有名为 ExecutionPolicy
的模板形参的重载按下列方式报告错误:
- 若作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy
为标准策略之一,则调用 std::terminate 。对于任何其他ExecutionPolicy
,行为是实现定义的。 - 若算法无法分配内存,则抛出 std::bad_alloc 。
可能的实现
template<class BidirIt, class OutputIt>
OutputIt reverse_copy(BidirIt first, BidirIt last, OutputIt d_first)
{
while (first != last) {
*(d_first++) = *(--last);
}
return d_first;
}
调用示例
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
#include <list>
struct Cell
{
int x;
int y;
Cell &operator+=(Cell &cell)
{
x += cell.x;
y += cell.y;
return *this;
}
};
std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
os << "{" << cell.x << "," << cell.y << "}";
return os;
}
int main()
{
auto func1 = []()
{
static Cell cell = {99, 100};
cell.x += 2;
cell.y += 2;
return cell;
};
std::vector<Cell> cells_1(6);
std::generate_n(cells_1.begin(), cells_1.size(), func1);
std::list<Cell> cells_2(8);
std::generate_n(cells_2.begin(), cells_2.size(), func1);
std::cout << "original : " << std::endl;
std::cout << "vector cells_1 : ";
std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
std::cout << std::endl;
std::cout << "list cells_2 : ";
std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
std::cout << std::endl << std::endl;
std::list<Cell> cells_3;
std::vector<Cell> cells_4;
std::reverse_copy(cells_1.begin(), cells_1.end(), std::back_inserter(cells_3));
std::reverse_copy(cells_2.begin(), cells_2.end(), std::back_inserter(cells_4));
std::cout << "reverse new : " << std::endl;
std::cout << "list cells_3 : ";
std::copy(cells_3.begin(), cells_3.end(), std::ostream_iterator<Cell>(std::cout, " "));
std::cout << std::endl;
std::cout << "vector cells_4 : ";
std::copy(cells_4.begin(), cells_4.end(), std::ostream_iterator<Cell>(std::cout, " "));
std::cout << std::endl << std::endl;
}