C++ STL 中的 list rbegin() 和 rend() 函式
在本文中,我們將討論 C++ STL 中 list::rbegin() 和 list::rend() 函式的工作原理、語法和示例。
什麼是 STL 中的列表 (List)?
列表是一種資料結構,允許在序列中的任何位置進行常數時間插入和刪除操作。列表實現為雙向連結串列。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在容器中任何位置進行元素的插入、提取和移動操作的效能更好。在列表中,直接訪問元素的速度較慢,列表類似於 forward_list,但 forward_list 物件是單向連結串列,只能向前迭代。
什麼是 list::rbegin()?
list::rbegin() 是 C++ STL 中的一個內建函式,在標頭檔案中宣告。rbegin() 是一個反向開始函式。rebegin() 返回一個反向迭代器,該迭代器指向列表的最後一個元素。反向迭代器是一種反向移動的迭代器,從末尾開始,向開頭移動。但是 back() 也返回最後一個元素,但與簡單的迭代器不同,這個雙向迭代器向後移動。
語法
list_container1.rbegin();
引數
此函式不接受任何引數。
示例
Input: list<int> List_container = {10, 11, 13, 15};
List_container.rbegin();
Output:
List= 15返回值
此函式返回一個反向迭代器,指向列表的最後一個元素。反向迭代器是一種向後移動的迭代器。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
list<int> myList = { 10, 20, 30, 40 };
cout<<"List is: ";
for (auto i = myList.rbegin(); i!= myList.rend(); ++i)
cout << *i << " ";
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
List is: 40 30 20 10
什麼是 list::rend()?
list::rend() 是 C++ STL 中的一個內建函式,在標頭檔案中宣告。rend() 是一個反向結束函式。rend() 返回一個反向迭代器,該迭代器指向與之關聯的列表容器的第一個元素之前的 position。反向迭代器是一種反向移動的迭代器,從末尾開始,向開頭移動。但是 back() 也返回最後一個元素,但與簡單的迭代器不同,這個雙向迭代器向後移動。
語法
list_container1.rend();
此函式不接受任何引數。
示例
Input: list<int> List_container= { 10, 11, 13, 15};
List_container.rend();
Output:
List= 5 //will display random value which is before the beginning of the list返回值
此函式返回一個反向迭代器,指向列表中第一個元素之前的元素。反向迭代器是一種向後移動的迭代器。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
list<int> myList = { 10, 20, 30, 40 };
cout<<"List is : ";
for (auto i = myList.rbegin(); i!= myList.rend(); ++i)
cout << *i << " ";
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
List is: 40 30 20 10
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP