我们需要知道 STL 中 list 是否为空,可以使用 size 函数获取其长度,看是否为 0,或者直接使用 empty 函数。
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
,如下图所示:
我们使用了 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
,如下图所示:
我们直接使用 empty 函数,根据 empty 函数的返回值,判断链表是否为空。
我们需要知道 STL 中 list 的是否为空,可以使用 size 函数获取其长度,看是否为 0,或者直接使用 empty 函数。