首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++ reverse函数的用法

C++ reverse函数的用法

作者头像
mathor
发布2018-06-22 10:38:54
发布2018-06-22 10:38:54
39.6K0
举报
文章被收录于专栏:mathormathor

逆序(反转)无论是在C或是C++中用的都特别多,常用于数组,字符串,容器等,其本身的函数参数也不复杂。

       标准C中是没有recerse()函数的,这是C++的一个新增函数,使用需要包含头文件

代码语言:javascript
复制
#include <algorithm>

       reverse函数用于反转在[first,last)范围内的顺序(包括first指向的元素,不包括last指向的元素),reverse函数没有返回值

代码语言:javascript
复制
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first,BidirectionalIterator last);

       例如,交换vector容器中元素的顺序

代码语言:javascript
复制
vector<int> v = {5,4,3,2,1};
reverse(v.begin(),v.end());//v的值为1,2,3,4,5

       还有string类的字符串

代码语言:javascript
复制
string str="www.mathor.top";
reverse(str.begin(),str.end());//str结果为pot.rohtam.wwww

       最后给出函数原型,该函数等价于通过调用iter_swap来交换元素位置

代码语言:javascript
复制
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
    while ((first!=last)&&(first!=--last))
    {
        std::iter_swap (first,last);
        ++first;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-03-14,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档