C++ List::crend() 函式



C++ 的 std::list::crend() 函式用於獲取一個指向反轉列表的最後一個元素之後元素的常量反向迭代器。

const_reverse_iterator 是一種迭代器,它向後迭代,同時指向一個常量迭代器。const_reverse_iterator 值確定它在列表容器中的起始位置和結束位置。但是,即使列表元素不是常量,它也不能用於修改它指向的內容。

語法

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

const_reverse_iterator crend() const;

引數

  • 它不接受任何引數。

返回值

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

示例 1

在下面的程式中,我們使用 C++ std::list::crend() 函式來獲取一個指向當前列表 {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.crend();
   cout<<"\nA constant 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::crend() 函式的另一個示例。這裡,我們建立了一個名為 char_list 的列表(型別為 char),其值為 {'a', 'b', 'c', 'd', 'e', 'f'}。然後使用 crend() 函式,我們試圖檢索一個指向反轉列表的最後一個元素之後的常量反向迭代器。

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

int main() {
   //create a list
   list<char> char_list = {'a', 'b', 'c', 'd', 'e', 'f'};
   cout<<"List elements are: ";
   for(char v : char_list) {
      cout<<v<<" ";
   }
   auto it = char_list.crend();
   cout<<"\nA constant reverse iterator of the last element: ";
   cout<<*it;
}

輸出

這將生成以下輸出:

List elements are: a b c d e f 
A constant reverse iterator of the last element: 

示例 3

如果列表型別是字串。

在此示例中,我們建立了一個名為 str_list 的列表(型別為 string),其值為 {"Java", "HTML", "CSS", "Angular"}。然後,使用 crend() 函式,我們試圖檢索一個指向反轉列表的最後一個元素之後的常量反向迭代器。

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

int main() {
   //create a list
   list<string> str_list  =  {"Java", "HTML", "CSS", "Angular"};
   cout<<"List elements are: ";
   for(string s : str_list ) {
      cout<<s<<" ";
   }
   auto it = str_list.crend();
   cout<<"\nA constant reverse iterator of the last element: ";
   cout<<*it;
}

輸出

上述程式產生以下輸出:

List elements are: Java HTML CSS Angular 
A constant reverse iterator of the last element:
Segmentation fault

示例 4

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

在此示例中,我們使用 crend() 函式以及 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 constant reverse iterator of an elements are : ";
   for (auto it = num_list.crbegin(); it != num_list.crend(); it++) {
      cout<<*it<<" ";
   }
}

輸出

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

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

© . All rights reserved.