C++ List::rbegin() 函数



C++ 的std::list::rbegin()函数用于获取一个反向迭代器,指向反转列表的第一个元素。它对应于非反转列表的最后一个元素。

在 C++ 中,迭代器是一个对象,用于指向 STL(标准模板库)容器的内存地址。我们使用(*)符号来检索迭代器指向的当前位置的元素。(*)符号在 C++ 中称为星号运算符。

如果列表为空,则返回的迭代器等于 rend()。

语法

以下是 C++ std::list::rbegin() 函数的语法 -

reverse_iterator rbegin();

参数

  • 它不接受任何参数。

返回值

此函数返回一个反向迭代器。

示例 1

在以下程序中,我们使用 C++ std::list::rbegin() 函数来获取一个反向迭代器,指向当前反转列表 {10, 20, 30, 40, 50} 的第一个元素。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {10, 20, 30, 40, 50};
   cout<<"List elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   auto ri = num_list.rbegin();
   cout<<"\nThe iterator of the last element: ";
   cout<<*ri;
}

输出

以下是上述程序的输出 -

List elements are: 10 20 30 40 50 
The iterator of the last element: 50

示例 2

除了 int 类型的列表元素外,您还可以检索任何其他类型的列表元素的迭代器,例如 char 和 string 列表内容。

以下是 C++ std::list::rbegin() 函数的另一个示例。在这里,我们创建一个名为 vowels 的列表(类型为 char),其值为 {'a', 'e', 'i', 'o', 'u'}。然后使用 rbegin() 函数,我们尝试获取一个反向迭代器,指向当前反转列表的第一个元素。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<char> vowels = {'a', 'e', 'i', 'o', 'u'};
   cout<<"List elements are: ";
   for(char v : vowels) {
      cout<<v<<" ";
   }
   auto ri = vowels.rbegin();
   cout<<"\nThe iterator of the last element: ";
   cout<<*ri;
}

输出

这将生成以下输出 -

List elements are: a e i o u 
The iterator of the last element: u

示例 3

如果列表类型是字符串。

在此示例中,我们创建一个名为 fname 的列表(类型为 string),其值为 {"Rohan", "Reema", "Geeta", "Seema"}。然后,使用 rbegin() 函数,我们尝试获取一个反向迭代器,指向当前反转列表的第一个元素。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<string> names = {"Rohan", "Reema", "Geeta", "Seema"};
   cout<<"List elements are: ";
   for(string s : names) {
      cout<<s<<" ";
   }
   auto ri = names.rbegin();
   cout<<"\nThe iterator of the last element: ";
   cout<<*ri;
}

输出

上述程序产生以下输出 -

List elements are: Rohan Reema Geeta Seema 
The iterator of the last element: Seema

示例 4

使用 for 循环以及 rbegin() 函数来检索容器元素的迭代器。

在此示例中,我们使用 rbegin() 函数以及 for 循环来遍历当前容器 {1, 2, 3, ,4 ,5} 并以反向顺序检索容器中所有元素的迭代器。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {1, 2, 3, 4 ,5};
   cout<<"List elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   cout<<"\nA reverse iterator of an elements are : ";
   for(auto i = num_list.rbegin(); i!=num_list.rend(); i++) {
      cout<<*i<<" ";
   }
}

输出

执行上述程序后,将产生以下输出 -

List elements are: 1 2 3 4 5 
A reverse iterator of an elements are : 5 4 3 2 1 
广告