C++ forward_list::cbegin() 函式



C++ 的 std::forward_list::cbegin() 函式用於獲取指向 forward_list 容器第一個元素的常量迭代器。

如果當前 forward_list 為空,則 cbegin() 函式返回的常量迭代器等於 end() 函式的結果。在 C++ 中,迭代器是一個可以遍歷 STL(標準模板庫)中元素並訪問單個元素的物件。

語法

以下是 C++ std::forward_list::cbegin() 函式的語法:

const_iterator cbegin() const;

引數

  • 它不接受任何引數。

返回值

此函式返回指向第一個元素的常量迭代器。

示例 1

如果 forward_list 非空且為 int 型別,則 cbegin() 函式返回指向第一個元素的常量迭代器。

在下面的示例中,我們使用 C++ std::forward_list::cbegin() 函式來獲取當前 forward_list {10, 20, 30, 40, 50} 的第一個元素的常量迭代器。

#include<iostream>
#include<forward_list>
using namespace std;
int main(){
   //create a forward_list
   forward_list<int> num_list = {10, 20, 30, 40, 50};
   cout<<"The num_list contents are: "<<endl;
   for(int n : num_list) {
      cout<<n<<endl;
   }
   //using the cbegin() function
   auto it = num_list.cbegin();
   cout<<"The constant iterator to the first element: "<<*it;
}

輸出

以下是上述程式的輸出:

The num_list contents are: 
10
20
30
40
50
The constant iterator to the first element: 10

示例 2

如果 forward_list 為 char 型別,則此函式返回指向此 forward_list 的第一個 char 元素的常量迭代器。

以下是 C++ d::forward_list::cbegin() 函式的另一個示例。在這裡,我們建立一個名為 char_list 的 forward_list(型別為 char),其內容為 {'A', 'B', 'C', 'D', 'E'}。然後,使用 cbegin() 函式,我們嘗試獲取此 forward_list 的第一個元素的常量迭代器。

#include<iostream>
#include<forward_list>
using namespace std;
int main() {
   //create a forward_list
   forward_list<char> char_list = {'A', 'B', 'C', 'D', 'E'};
   cout<<"The char_list contents are: "<<endl;
   for(char c : char_list) {
      cout<<c<<endl;
   }
   //using the cbegin() function
   auto it = char_list.cbegin();
   cout<<"The constant iterator to the first element: "<<*it;
}

輸出

這將生成以下輸出:

The char_list contents are: 
A
B
C
D
E
The constant iterator to the first element: A

示例 3

使用 for 迴圈以及 cbegin() 函式遍歷容器並獲取從第一個元素開始的所有元素的常量迭代器。

在下面的程式中,我們建立一個名為 colors 的 forward_list(型別為 string),其內容為 {"Red", "Green", "Blue", "Black"}。然後,使用 for 迴圈以及 cbegin() 函式遍歷此 forward_list 並獲取從第一個元素開始的所有元素的常量迭代器。

#include<iostream>
#include<forward_list>
using namespace std;
int main(){
   //create a forward_list
   forward_list<string> colors = {"Red", "Green", "Blue", "Black"};
   cout<<"The iterator of all the elements are: "<<endl;
   for(auto it = colors.cbegin(); it != colors.end(); it++){
      cout<<*it<<endl;
   }
}

輸出

上述程式產生以下輸出:

The iterator of all the elements are: 
Red
Green
Blue
Black

示例 4

如果 forward_list 為空,則返回的常量迭代器等於 end() 函式的結果。

#include<iostream>
#include<forward_list>
using namespace std;
int main(){
   //create a forward_list
   forward_list<string> fruits = {};
   cout<<"The size of this forward_list is: "<<endl;
   cout<<distance(fruits.begin(), fruits.end())<<endl;
   cout<<"The iterator of all the elements are: "<<endl;
   //using the cbegin() function
   auto it = fruits.cbegin();
   cout<<*it<<endl;
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

The size of this forward_list is: 
0
The iterator of all the elements are: 
Segmentation fault
廣告

© . All rights reserved.