一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
定义于头文件 <algorithm>

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

逆转范围中的元素顺序

std::reverse

1) 反转 [first, last) 范围中的元素顺序

表现如同应用 std::iter_swap 到对于非负 i < (last-first)/2 的每对迭代器 first+i, (last-i) - 1

2) 同 (1) ,但按照 policy 执行。此重载仅若 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true 才参与重载决议。

参数

first, last - 要反转的元素的范围
policy - 所用的执行策略。细节见执行策略。
类型要求
BidirIt 必须满足值可交换 (ValueSwappable) 和 遗留双向迭代器 (LegacyBidirectionalIterator) 的要求。

返回值
  (无)

异常
  拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:

  • 若作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy 为标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,行为是实现定义的。
  • 若算法无法分配内存,则抛出 std::bad_alloc 。

可能的实现

1 template<class BidirIt>
2 void reverse(BidirIt first, BidirIt last)
3 {
4     while ((first != last) && (first != --last)) {
5         std::iter_swap(first++, last);
6     }
7 }

调用示例

 1 #include <algorithm>
 2 #include <functional>
 3 #include <iostream>
 4 #include <iterator>
 5 #include <vector>
 6 #include <list>
 7  
 8 struct Cell
 9 {
10     int x;
11     int y;
12     Cell &operator+=(Cell &cell)
13     {
14         x += cell.x;
15         y += cell.y;
16         return *this;
17     }
18 };
19  
20 std::ostream &operator<<(std::ostream &os, const Cell &cell)
21 {
22     os << "{" << cell.x << "," << cell.y << "}";
23     return os;
24 }
25  
26 int main()
27 {
28     auto func1 = []()
29     {
30         static Cell cell = {99, 100};
31         cell.x += 2;
32         cell.y += 2;
33         return cell;
34     };
35  
36     std::vector<Cell> cells_1(6);
37     std::generate_n(cells_1.begin(), cells_1.size(), func1);
38     std::list<Cell> cells_2(8);
39     std::generate_n(cells_2.begin(), cells_2.size(), func1);
40  
41     std::cout << "original : " << std::endl;
42     std::cout << "cells_1 : ";
43     std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
44     std::cout << std::endl;
45     std::cout << "cells_2 : ";
46     std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
47     std::cout << std::endl << std::endl;
48  
49     std::reverse(cells_1.begin(), cells_1.end());
50     std::reverse(cells_2.begin(), cells_2.end());
51     std::cout << "reverse new : " << std::endl;
52     std::cout << "cells_1 : ";
53     std::copy(cells_1.begin(), cells_1.end(), std::ostream_iterator<Cell>(std::cout, " "));
54     std::cout << std::endl;
55     std::cout << "cells_2 : ";
56     std::copy(cells_2.begin(), cells_2.end(), std::ostream_iterator<Cell>(std::cout, " "));
57     std::cout << std::endl << std::endl;
58 }

输出

posted on 2024-03-26 11:47  一杯清酒邀明月  阅读(195)  评论(0编辑  收藏  举报