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