當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::reverse()用法及代碼示例


reverse()是頭文件算法中的預定義函數。在上述頭文件中將其定義為模板。它反轉任何容器的[first,last)範圍內的元素順序。
注意:使用的範圍是[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 program to illustrate 
// std::reverse() function of STL 
#include<iostream> 
#include<algorithm> 
#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


相關用法


注:本文由純淨天空篩選整理自 std::reverse() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。