STL list是否为空

STL list是否为空教程

我们需要知道 STLlist 是否为空,可以使用 size 函数获取其长度,看是否为 0,或者直接使用 empty 函数。

STL list是否为空

语法

list1.empty()

参数

参数 描述
list1 需要判断是否为空的链表。

返回值

为空,返回 true,否则,返回 false。

案例

链表是否为空

使用 size 获取链表长度,判断是否为空

#include <iostream> #include <list> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; list<string> list1; if (list1.size() == 0) { cout << "list1 is empty()" << endl; } else { cout << "list1 is not empty()" << endl; } return 0; }

因为,这里需要使用 C++ 11,因此,我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ list.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

74_C STL list是否为空.png

我们使用了 size 获取了链表的长度,并根据长度是否为 0,判断链表是否为空。

链表是否为空

使用 empty 函数,判断链表是否为空

#include <iostream> #include <list> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; list<string> list1; if (list1.empty()) { cout << "list1 is empty()" << endl; } else { cout << "list1 is not empty()" << endl; } return 0; }

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

75_C STL list是否为空.png

我们直接使用 empty 函数,根据 empty 函数的返回值,判断链表是否为空。

STL list是否为空总结

我们需要知道 STL 中 list 的是否为空,可以使用 size 函数获取其长度,看是否为 0,或者直接使用 empty 函数。