C++ forward_list::begin() 函数



C++ 的std::forward_list::begin()函数用于检索指向forward_list容器第一个元素的迭代器。

如果当前forward_list为空,则begin()函数返回的迭代器等于end()函数的结果。在C++中,迭代器是一个可以迭代STL(标准模板库)中元素并提供对单个元素访问的对象。

语法

以下是C++ std::forward_list::begin()函数的语法:

iterator begin();

参数

  • 它不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回指向第一个元素的迭代器。

示例 1

如果forward_list非空且为int类型,则begin()函数返回指向第一个元素的迭代器。

在以下示例中,我们使用C++ std::forward_list::begin()函数来检索当前forward_list {1, 2, 3, 4, 5}的第一个元素的迭代器。

Open Compiler
#include<iostream> #include<forward_list> using namespace std; int main(){ //create a forward_list forward_list<int> num_list = {1, 2, 3, 4, 5}; cout<<"The num_list contents are: "<<endl; for(int n : num_list) { cout<<n<<endl; } //using the begin() function auto it = num_list.begin(); cout<<"The iterator to the first element: "<<*it; }

输出

以下是上述程序的输出:

The num_list contents are: 
1
2
3
4
5
The iterator to the first element: 1

示例 2

如果forward_list为char类型,则此函数返回指向此forward_list的第一个char元素的迭代器。

以下是C++ d::forward_list::begin()函数的另一个示例。在这里,我们创建了一个名为char_list的forward_list(char类型),其内容为{'a', 'b', 'c', 'd', 'e'}。然后,使用begin()函数,我们尝试检索此forward_list第一个元素的迭代器。

Open Compiler
#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 begin() function auto it = char_list.begin(); cout<<"The iterator to the first element: "<<*it; }

输出

这将生成以下输出:

The char_list contents are: 
a
b
c
d
e
The iterator to the first element: a

示例 3

使用for循环以及begin()函数遍历容器并检索从第一个元素开始的所有元素的迭代器。

在以下程序中,我们创建了一个名为fruits的forward_list(string类型),其内容为{"Apple", "Banana", "Orange", "Grapes"}。然后,使用for循环以及begin()函数遍历此forward_list并检索从第一个元素开始的所有元素的迭代器。

Open Compiler
#include<iostream> #include<forward_list> using namespace std; int main(){ //create a forward_list forward_list<string> fruits = {"Apple", "Banana", "Orange", "Grapes"}; cout<<"The iterator of all the elements are: "<<endl; for(auto it = fruits.begin(); it != fruits.end(); it++){ cout<<*it<<endl; } }

输出

上述程序产生以下输出:

The iterator of all the elements are: 
Apple
Banana
Orange
Grapes

示例 4

如果forward_list为空,则返回的迭代器等于end()函数的结果。

Open Compiler
#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 begin() function auto it = fruits.begin(); cout<<*it<<endl; }

输出

执行上述程序后,它将产生以下输出:

The size of this forward_list is: 
0
The iterator of all the elements are: 
Segmentation fault (core dumped)
广告