📜  C++中的std :: reverse()

📅  最后修改于: 2021-05-30 16:42:56             🧑  作者: Mango

reverse()是头文件算法中的预定义函数。在上述头文件中将其定义为模板。它将反转任何容器的[first,last)范围内的元素顺序。时间复杂度为O(n)。
注意:所使用的范围是[first,last),它包含first和last之间的所有元素,包括first指向的元素,但last指向的元素。
句法:

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 
#include 
#include 
using namespace std;
  
int main()
{
    vector vec1;
    vector::iterator p;
  
    // Inserting elements in vector
    for (int i = 0; i < 8; i++) {
        vec1.push_back(i + 10);
    }
    // Displaying elements of vector
    cout<<"Initial Vector:"< vec2{ 4, 5, 6, 7 };
  
    cout<<"Initial Vector:"<


输出:

Initial Vector:
10 11 12 13 14 15 16 17 
Reverse only from index 5 to 7 in vector:
10 11 12 13 14 17 16 15 

Initial Vector:
4 5 6 7 
Reverse full Vector:
7 6 5 4 

时间复杂度: O(n)

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”