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

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

#include <algorithm>

       reverse函数用于反转在[first,last)范围内的顺序(包括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.mathor.top";
reverse(str.begin(),str.end());//str结果为pot.rohtam.wwww

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

template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
      
    while ((first!=last)&&(first!=--last))
    {
      
        std::iter_swap (first,last);
        ++first;
    }