C++ STL 中的 forward_list::clear() 和 forward_list::erase_after()
本文将讨论 C++ 中 forward_list::clear() 和 forward_list::erase_after() 函数的工作原理、语法和示例。
什么是 STL 中的 Forward_list?
Forward list 是允许在序列中的任何位置进行常数时间插入和删除操作的顺序容器。Forward list 以单链表的形式实现。顺序通过将每个元素与序列中下一个元素的链接来保持。
什么是 forward_list::clear()?
forward_list::clear() 是 C++ STL 中一个内置函数,声明在 <forward_list> 头文件中。当需要一次性删除 forward list 中所有元素时,使用 clear()。此函数会销毁 forward list 的所有元素,并将 forward list 的大小设置为零。
语法
flist_container1.clear();
参数
此函数不接受任何参数。
返回值
此函数不返回任何值。
示例
Input: forward_list<int> forward = {1, 2, 3, 4};
forward.clear();
forward.size();
Output: 0示例
#include <forward_list>
#include <iostream>
using namespace std;
int main(){
forward_list<int> myList = { 10, 20, 30, 40 };
myList.clear();
for (auto i = myList.begin(); i!= myList.end(); ++i)
cout << ' ' << *i;
cout<<"List is cleared";
return 0;
}输出
如果运行以上代码,将生成以下输出:
List is cleared
什么是 forward_list::erase_after()?
forward_list::erase_after() 是 C++ STL 中一个内置函数,声明在 <forward_list> 头文件中。erase_after() 用于删除 forward list 中特定位置之后的所有元素。forward list 的大小将减少已删除的元素数量。
语法
flist_container1.erase_after(unsigned int position);
参数
此函数接受一个参数,即要从中删除元素的位置。
返回值
此函数不返回任何值。
示例
Input: forward_list<int> forward = {1, 2, 3, 4};
forward.erased_after(2);
Output:
Forward list after erase_after() = 1 2 3示例
#include <forward_list>
#include <iostream>
using namespace std;
int main(){
forward_list<int> myList = { 10, 20, 30, 40, 50 };
forward_list<int>::iterator i;
i = myList.begin();
myList.erase_after(i);
cout<<"Elements are : ";
for (auto i = myList.begin(); i!= myList.end(); ++i)
cout << ' ' << *i;
return 0;
}输出
如果运行以上代码,将生成以下输出:
Elements are : 10 30 40 50
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP