C++ STL 中的 list crbegin() 和 crend() 函式


給定任務是展示 C++ 中 list crbegin() 和 crend() 函式的工作原理。

list::crbegin() 和 list::crend() 函式是 C++ 標準模板庫的一部分。

需要包含 <list> 標頭檔案才能呼叫這些函式。

  • list::crbegin()

    此函式返回一個常量迭代器,該迭代器指向列表的末尾元素,這將是列表的反向開頭。它可以用於列表的反向遍歷,但不能更改列表中的值,這意味著 crbegin() 函式只能用於迭代。

語法

List_Name.crbegin()

引數

該函式不接受任何引數。

返回值

該函式返回一個常量反向迭代器,該迭代器指向列表的反向開頭元素,即列表的末尾。

  • list::crend()

    此函式返回一個常量迭代器,該迭代器指向列表的末尾元素。它可以用於列表的反向遍歷,但不能更改列表中的值,這意味著 crend() 函式只能用於迭代。

語法

List_Name.crend()

引數

該函式不接受任何引數。

返回值

該函式返回一個常量反向迭代器,該迭代器指向列表的反向末尾,即列表的開頭。

示例

Input: list<int> Lt={99,34,55}
Output: The last element is 55

**解釋** -

這裡我們建立了一個包含元素 99、34 和 55 的列表。然後我們呼叫了 crbegin() 函式,它指向列表的反向開頭,即列表的末尾。

因此,當我們列印它時,生成的輸出為 55,它是列表的最後一個元素。

**下面程式中使用的方案如下** -

  • 首先建立一個列表,我們稱之為“Ld”,型別為 int,併為其分配一些值。
  • 然後開始一個迴圈遍歷列表。
  • 然後在迴圈內建立一個名為“itr”的 auto 型別物件,用於儲存 crend() 和 crbegin() 函式的返回值。透過使用 crend() 函式傳遞列表的第一個元素來初始化“itr”。
  • 然後透過編寫“itr”不等於使用 crbegin() 函式得到的列表的最後一個元素來指定迴圈的終止條件。
  • 列印 *itr 的值。

演算法

Start
Step 1->In function main()
   Initialize list<int> Lt={}
   Loop For auto itr = Lt.crend() and itr != Lt.crbegin() and itr++
   Print *itr
   End
Stop

示例

 線上演示

#include<iostream>
#include<list>
using namespace std;
int main() {
   list<int> Lt = { 33,44,55,66 };
   //Printing the elements of the list
   cout <<"The elements of the list are : " <<"\n";
   for (auto itr = Lt.crend(); itr != Lt.crbegin(); itr++)
   cout << *itr << " ";
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出 -

The elements of the list are :
4

更新於: 2020年1月20日

81 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.