C++ STL 中的 forward_list::front() 和 forward_list::empty()
c++server side programmingprogramming更新于 2025/4/23 6:37:17
在本文中,我们将讨论 C++ 中 forward_list::front() 和 forward_list::empty() 函数的工作原理、语法和示例。
STL 中的 Forward_list 是什么?
前向列表是序列容器,允许在序列中的任何位置进行常量时间插入和删除操作。前向列表实现为单链表。顺序由与序列中下一个元素的链接的每个元素的关联来保持。
什么是 forward_list::front()?
forward_list::front() 是 C++ STL 中的内置函数,在 <forward_list> 头文件中声明。 front() 返回指向 forward_list 容器中第一个元素的迭代器。
语法
forwardlist_container.front();
此函数不接受任何参数。
返回值
此函数返回指向容器第一个元素的迭代器。
示例
/* 在下面的代码中,我们创建一个前向列表并向其中插入元素,然后我们将调用 front() 函数来获取前向列表中的第一个元素。 */
#include <forward_list> #include <iostream> using namespace std; int main(){ forward_list<int> forwardList = {2, 6, 1, 0 }; cout<<"my first element in a forward list is: "; cout<<forwardList.front(); return 0; }
输出
如果我们运行上述代码,它将生成以下输出
my first element in a forward list is: 2
什么是 forward_list::empty()?
forward_list::empty() 是 C++ STL 中的一个内置函数,在 <forward_list> 头文件中声明。如果转发列表容器为空,empty() 返回 true,否则返回 false。此函数检查容器的大小是否为 0
语法
bool forwardlist_container.empty();
此函数不接受任何参数。
返回值
如果容器的大小为 0,此函数返回 true,否则返回 false
示例
/* 在下面的代码中,我们创建了一个转发列表,然后我们将通过调用 empty() 函数来检查列表是否显示为空。之后,我们将元素插入到前向列表中,然后再次调用empty()函数来检查现在的结果。 */
#include <forward_list> #include <iostream> using namespace std; int main(){ forward_list<int> forwardList = {}; if (forwardList.empty()){ cout << "Yess forward list is empty\n"; } forwardList = {1, 3, 4, 5}; if (forwardList.empty()){ cout << "Yess forward list is empty\n"; } else { cout << "No forward list is not empty\n"; } return 0; }
输出
如果我们运行上述代码,它将生成以下输出
Yess forward list is empty No forward list is not empty