📌  相关文章
📜  C++ STL中的forward_list :: front()和forward_list :: empty()(1)

📅  最后修改于: 2023-12-03 15:13:56.318000             🧑  作者: Mango

C++ STL中的forward_list::front()和forward_list::empty()
1. 什么是forward_list?

forward_list是C++ STL中的容器类型之一,是一个单向链表,每个节点只连接到下一个节点。

2. forward_list::front()是什么?

forward_list::front()是一个函数,用于返回链表中第一个元素的引用。

3. forward_list::empty()是什么?

forward_list::empty()是一个函数,用于判断链表是否为空,即链表中是否有元素。

4. 代码示例

以下是一个简单的代码示例,展示了如何使用forward_list::front()和forward_list::empty()函数:

#include <iostream>
#include <forward_list>

int main() {
    std::forward_list<int> myList = {1, 2, 3, 4, 5};

    if (!myList.empty()) {
        int frontElement = myList.front();
        std::cout << "The front element of the list is : " << frontElement << std::endl;
    } else {
        std::cout << "The list is empty!" << std::endl;
    }

    return 0;
}
5. 输出结果

当代码运行时,输出的结果如下:

The front element of the list is : 1

在这个例子里,我们首先创建了一个forward_list类型的对象,名为myList,并在其中添加了五个整数。接着我们使用forward_list::empty()函数判断了myList是否为空,并得到返回结果为false,即myList中有元素。因此,我们使用forward_list::front()函数取得了myList中第一个元素的引用,并将其输出。

如果myList为空,代码片段将输出“The list is empty!”而不是myList中的第一个元素。

6. 总结

使用forward_list可以方便地进行单向链表的操作,使用forward_list::front()可以快速获得链表中第一个元素的引用,使用forward_list::empty()可以判断链表是否为空。