如果我们需要删除 STL 中的 list 容器中的元素,我们除了可以使用 list 本身的函数,还可以使用一些全局函数。
成员函数 | 功能 |
---|---|
pop_front() | 删除位于 list 容器头部的一个元素。 |
pop_back() | 删除位于 list 容器尾部的一个元素。 |
erase() | 该成员函数既可以删除 list 容器中指定位置处的元素,也可以删除容器中某个区域内的多个元素。 |
clear() | 删除 list 容器存储的所有元素。 |
remove(val) | 删除容器中所有等于 val 的元素。 |
unique() | 删除容器中相邻的重复元素,只保留一份。 |
remove_if() | 删除容器中满足条件的元素。 |
使用 pop_front 删除 list 第一个元素
#include <iostream>
#include <list>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
list<string> list1{"Hello", "World", "HaiCoder", "www.haicoder.net"};
list1.pop_front();
for (auto&& value : list1)
{
cout << value << " ";
}
cout << endl;
list1.pop_front();
for (auto&& value : list1)
{
cout << value << " ";
}
cout << endl;
return 0;
}
因为,这里需要使用 C++ 11,因此,我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ list.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了 list 的 pop_front 删除了第一个元素。
使用 pop_back 删除 list 最后一个元素
#include <iostream>
#include <list>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
list<string> list1{"Hello", "World", "HaiCoder", "www.haicoder.net"};
list1.pop_back();
for (auto&& value : list1)
{
cout << value << " ";
}
cout << endl;
list1.pop_back();
for (auto&& value : list1)
{
cout << value << " ";
}
cout << endl;
return 0;
}
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了 list 的 pop_back 删除了最后一个元素。
使用 clear 清空 list 元素
#include <iostream>
#include <list>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
list<string> list1{"Hello", "World", "HaiCoder", "www.haicoder.net"};
list1.clear();
cout << "Size = " << list1.size() << endl;
return 0;
}
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了 list 的 clear 方法清空了 list 的元素。
使用 remove 删除链表所有某个值
#include <iostream>
#include <list>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
list<string> list1{"Hello", "World", "Hello", "www.haicoder.net"};
list1.remove("Hello");
for (auto&& value : list1)
{
cout << value << " ";
}
cout << endl;
return 0;
}
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了 list 的 remove 方法删除了 list 中所有的值为 Hello 的元素。
如果我们需要删除 STL 中的 list 容器中的元素,我们除了可以使用 list 本身的函数,还可以使用一些全局函数。