本篇学习forward_list删除操作
clear:清除内容
erase_after:擦除元素后的元素
pop_front:移除首元素
max_size:返回可容纳的最大元素数
代码实现:
#include <forward_list>
#include <iostream>
#include <sstream>
#include <time.h>
using namespace std;
void deleteElement()
{
//1.clear删除内容
forward_list<int> list1 = {22, 25, 27, 30, 33, 36, 39, 41, 42};
cout << "list1 的值: ";
for(auto &val: list1)
cout << val << "\t";
cout << endl;
//1.erase_after擦除pos元素之后的值,并返擦除的元素之后的迭代器
auto it1 = list1.erase_after(list1.before_begin());//擦除首元素,即删除22,返回25
cout << "it1 = " << *it1 << endl;
cout << "list1 的值: ";
for(auto &val: list1)
cout << val << "\t";
cout << endl;
//擦除第2个元素,返回第三个元素的迭代器,即删除27返回30
auto it2 = list1.erase_after(list1.begin());
cout << "it2 = " << *it2 << endl;
cout << "list1 的值: ";
for(auto &val: list1)
cout << val << "\t";
cout << endl;
//范围删除 25 30 33 36 39 41 42
auto start = std::next(list1.begin());//第2个位置开始 30
auto end = std::next(start, 4);//终点 41
cout << "start = " << *start << " end = " << *end << endl;
//删除范围(start, end)不包括start, end两个点
list1.erase_after(start, end);
cout << "list1 的值: ";
for(auto &val: list1)
cout << val << "\t";
//25 30 41 42
cout << endl;
//3.pop_front:移除首元素
list1.pop_front();//无返回值
cout << "list1 的值: ";
for(auto &val: list1)
cout << val << "\t";
//30 41 42
cout << endl;
//4.max_size:返回可容纳的最大元素数
cout << "list1.max_size = " << list1.max_size() << endl;
cout << endl;
}
int main()
{
deleteElement();
cout << endl;
cout << "Hello World!" << endl;
return 0;
}
运行结果:
clear是删除所有肉容,而erase_after是擦除一个值或一个范围里的值。
参考
https://zh.cppreference.com/w/cpp/container/forward_list
http://www.cplusplus.com/reference/forward_list/forward_list/