C++11标准模板(STL) 算法(std::reverse)
定义于头文件 <algorithm>
算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为[first, last)
,其中last
指代要查询或修改的最后元素的后一个元素。
逆转范围中的元素顺序
std::reverse1) 反转 [first, last) 范围中的元素顺序
表现如同应用 std::iter_swap 到对于非负 i < (lastfirst)/2 的每对迭代器 first+i, (lasti) 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 7 }调用示例
1 #include <algorithm> 2 #include <functional> 3 #include <iostream> 4 #include <iterator> 5 #include <vector> 6 #include <list> 7 8 struct Cell 9 18 }; 19 20 std::ostream &operator<<(std::ostream &os, const Cell &cell) 21 "; 23 return os; 24 } 25 26 int main() 27 ; 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 }输出
上一篇:Qt QTableView、QTableWidget设置表头
C/C++
lbc文件怎么看,lbc文件用什么打开?
lab文件怎么看,lab文件用什么打开?
pim文件怎么看,pim文件用什么打开?
pip文件怎么看,pip文件用什么打开?
pig文件怎么看,pig文件用什么打开?
pid文件怎么看,pid文件用什么打开?
pie文件怎么看,pie文件用什么打开?
0文件怎么看,0文件用什么打开?
picnc文件怎么看,picnc文件用什么打开?
pict文件怎么看,pict文件用什么打开?