C++ STL 中的 list::cbegin() 和 cend() 函式
給定任務是展示 C++ 中 list::cbegin() 和 list::cend() 函式的工作原理。
list::cbegin() 和 list::cend() 函式是 C++ 標準模板庫的一部分。
<list> 標頭檔案應該被包含以呼叫這些函式。
- list::cbegin()
此函式返回一個常量迭代器,該迭代器指向列表的起始元素。它可以用於遍歷列表,但不能更改列表中的值,這意味著 cbegin() 函式只能用於迭代。
語法
List_Name.cbegin();
引數
該函式不接受任何引數。
返回值
該函式返回一個常量迭代器,指向列表的起始元素。
- list::cend()
此函式返回一個常量迭代器,該迭代器指向列表的結束元素。它可以用於回溯列表,但不能更改列表中的值,這意味著 cend() 函式只能用於迭代。
語法
List_Name.cend();
引數
該函式不接受任何引數。
返回值
該函式返回一個常量迭代器,指向列表的結束元素。
示例
Input: list<int> Lt={4,8,9} Output: 4
**解釋** - 在這裡,我們建立了一個包含元素 4、8、9 的列表。然後我們呼叫了指向列表第一個元素的 cbegin() 函式。
因此,當我們列印它時,生成的輸出為 4,它是列表的第一個元素。
下面程式中使用的演算法如下:
- 首先建立一個列表,例如“Ld”,型別為 int,併為其分配一些值。
- 然後開始一個迴圈以列印列表中的元素。
- 然後在 for 迴圈內建立一個型別為 auto 的物件“itr”,用於接收 cend() 和 cbegin() 函式的返回值。透過使用 cbegin() 函式將“itr”分配給列表的第一個元素來初始化“itr”。
- 然後透過編寫“itr”不等於使用 cend() 函式獲得的列表的最後一個元素來指定 for 迴圈的終止條件。
- 列印 *itr 的值。
演算法
Start Step 1->In function main() Initialize list<int> Lt={} Loop For auto itr = Lt.cbegin() and itr != Lt.cend() and itr++ Print *itr End Stop
示例
#include<iostream> #include<list> using namespace std; int main() { list<int> Lt = { 4,1,7,9,6 }; //Printing the elements of the list cout <<"The elements of the list are : " <<"\n"; for (auto itr = Lt.cbegin(); itr != Lt.cend(); itr++) cout << *itr << " "; return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
4 1 7 9 6
廣告