# C++中的std::reverse()介绍和用法实例

2021年3月14日14:44:29 发表评论 397 次浏览

reverse()是头文件算法中的预定义函数。在上述头文件中将其定义为模板。它将反转任何容器的[first, last)范围内的元素顺序。时间复杂度为O(n)。

void reverse(BidirectionalIterator first, BidirectionalIterator last)
BidirectionalIterator is an iterator that can be used to access any
elements of a container in both forward and backward direction.

Input : 10 11 12 13 14 15 16 17
Output :10 11 12 13 14 17 16 15
Explanation:
reverse(v.begin() + 5, v.begin() + 8);
In the above function, input we have applied reverse() on the vector
from index 5 to index 7.
Therefore when we display the vector we get reverse order
from index 5 to index 7.

## CPP

// CPP program to illustrate
// std::reverse() function of STL
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector< int > v;

// Inserting elements in vector
for ( int i = 0; i < 8; i++)
v.push_back(i + 10);

cout << "Reverse only from index 5 to 7 in array:\n" ;
// Reversing elements from index 5 to index 7
reverse(v.begin() + 5, v.begin() + 8);

// Displaying elements of vector
vector< int >::iterator it;

for (it = v.begin(); it != v.end(); it++)
cout << (*it) << " " ;

// Reversing directly from beginning to end
cout << "\nReverse full array:\n" ;

int a[] = { 4, 5, 6, 7 };
std::reverse(std::begin(a), std::end(a));

// Print the array
std::cout << a[0] << a[1] << a[2] << a[3] << '\n' ;
return 0;
}

Reverse only from index 5 to 7 in array:
10 11 12 13 14 17 16 15
Reverse full array:
7654