逆序(反转)无论是在 C 或是 C++ 中用的都特别多,常用于数组,字符串,容器等,其本身的函数参数也不复杂。
标准 C 中是没有 recerse()
函数的,这是 C++ 的一个新增函数,使用需要包含头文件
- #include <algorithm>
reverse 函数用于反转在 [first,last) 范围内的顺序(左闭右开),reverse()
没有返回值
- template <class BidirectionalIterator>
- void reverse (BidirectionalIterator first,BidirectionalIterator last);
例如,交换 vector 容器中元素的顺序
- vector<int> v = {5,4,3,2,1};
- reverse(v.begin(),v.end());//v的值为1,2,3,4,5
还有 string 类的字符串
- string str="www.wmathor.com";
- reverse(str.begin(),str.end());//str结果为moc.rohtamw.wwww
最后给出函数原型,该函数等价于通过调用 iter_swap 来交换元素位置
- template <class BidirectionalIterator>
- void reverse (BidirectionalIterator first, BidirectionalIterator last)
- {
- while ((first!=last)&&(first!=--last))
- {
- std::iter_swap (first,last);
- ++first;
- }
- }
贺电贺电~~大佬什么时候搞个注册功能呀。。
大三吧