在本文中,我们将讨论C ++中forward_list::clear()和forward_list::erase_after()函数的工作原理,语法和示例。
转发列表是序列容器,允许在序列中的任何位置进行恒定时间的插入和擦除操作。转发列表被实现为单链接列表。通过与到序列中下一个元素的链接的每个元素的关联来保持顺序。
forward_list::clear()是C ++ STL中的内置函数,在<forward_list>头文件中声明。clear()
当我们必须一次删除转发列表中的所有元素时使用。此函数销毁转发列表的所有元素,并使转发列表的大小为零。
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()是C ++ STL中的内置函数,在<forward_list>头文件中声明。当我们要删除特定位置之后的前向列表中的元素时,将使用Erase_after()。转发列表的大小通过删除的元素数减少。
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