C++ List::rend() 函式



C++ 的std::list::rend()函式用於檢索一個反向迭代器,該迭代器指向反轉列表的最後一個元素之後的元素。

此函式對應於非反轉列表的第一個元素之前的元素。此列表中的元素充當佔位符,嘗試訪問它會導致未定義的行為。在 C++ 中,迭代器用於指向 STL(標準模板庫)容器的記憶體地址。

rend() 函式類似於 crend() 函式,其中 crend() 函式返回一個指向反轉列表的最後一個元素之後的元素的常量反向迭代器,而 rend() 函式返回一個指向反轉列表的最後一個元素之後的元素的反向迭代器。

語法

以下是 C++ std::list::rend() 函式的語法:

const_reverse_iterator rend();

引數

  • 它不接受任何引數。

返回值

此函式返回一個反向迭代器,該迭代器指向反轉列表的最後一個元素之後的元素。

示例 1

在下面的程式中,我們使用 C++ std::list::rend() 函式來檢索一個反向迭代器,該迭代器指向當前列表 {10, 20, 30, 40} 的最後一個元素之後的元素。

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

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

輸出

以下是上述程式的輸出:

List elements are: 10 20 30 40 
A constant reverse iterator of the last element: 4

示例 2

除了 int 型別的列表元素外,您還可以檢索任何其他型別的列表元素(如 char 和 string 列表內容)的迭代器。

以下是 C++ std::list::rend() 函式的另一個示例。在這裡,我們建立一個名為 symbols 的列表(型別為 char),其值為 {'@', '#', '$', '%', '&', '*'}. 然後使用 rend() 函式,我們嘗試檢索一個反向迭代器,該迭代器指向反轉列表的最後一個元素之後。

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

int main() {
   //create a list
   list<char> symbols  = {'@', '#', '$', '%', '&', '*'};
   cout<<"List elements are: ";
   for(char v : symbols) {
      cout<<v<<" ";
   }
   auto it = symbols.rend();
   cout<<"\nA reverse iterator of the last element: ";
   cout<<*it;
}

輸出

這將生成以下輸出:

List elements are: @ # $ % & * 
A reverse iterator of the last element: 

示例 3

如果列表型別是字串。

在此示例中,我們建立一個名為 names 的列表(型別為 string),其值為 {"Mukesh", "Rahul", "Mohan", "Shavita"}。然後,使用 rend() 函式,我們嘗試檢索一個反向迭代器,該迭代器指向反轉列表的最後一個元素之後。

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

int main() {
   //create a list
   list<string> names = {"Mukesh", "Rahul", "Mohan", "Shavita"};
   cout<<"List elements are: ";
   for(string s : names ) {
      cout<<s<<" ";
   }
   auto it = names.rend();
   cout<<"\nA reverse iterator of the last element: ";
   cout<<*it;
}

輸出

上述程式產生以下輸出:

List elements are: Mukesh Rahul Mohan Shavita 
A reverse iterator of the last element: 
Segmentation fault

示例 4

使用 for 迴圈以及 rend() 函式來檢索反轉列表的反向迭代器。

在此示例中,我們使用 rend() 函式以及 for 迴圈來遍歷當前容器 {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10} 並檢索反轉列表所有元素的反向迭代器。

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

int main() {
   //create a list
   list<int> num_list = {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10} ;
   cout<<"List elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   cout<<"\nThe reverse iterator of an elements are : ";
   for (auto it = num_list.crbegin(); it != num_list.rend(); it++) {
      cout<<*it<<" ";
   }
}

輸出

執行上述程式後,它將產生以下輸出:

List elements are: 1 2 3 4 5 6 7 8 9 10 
The reverse iterator of an elements are : 10 9 8 7 6 5 4 3 2 1 
廣告

© . All rights reserved.