C++ STL 中的 List::clear()


在本文中,我们将讨论 C++ 中 list::clear() 函数的工作原理、语法和示例。

什么是 STL 中的 List?

List 是一种数据结构,它允许在序列中的任何位置进行常数时间插入和删除操作。列表以双向链表的形式实现。列表允许非连续内存分配。与数组、向量和双端队列相比,列表在任何位置插入、提取和移动元素方面表现更好。在列表中,对元素的直接访问速度较慢,并且列表类似于 forward_list,但 forward_list 对象是单向链表,它们只能向前迭代。

什么是 clear()?

list::clear() 是 C++ STL 中的一个内置函数,它在头文件中声明。list::clear() 清空整个列表。换句话说,clear() 删除列表容器中存在的所有元素,并使容器的大小为 0。

语法

list_name.clear();

此函数不接受任何参数。

返回值

此函数不返回任何内容,只是从容器中删除所有元素。

示例

在下面的代码中,我们将元素插入列表,然后应用 clear 函数清空整个列表,使其为空。

 实时演示

#include <iostream>
#include <list>
using namespace std;
int main(){
   list<int> myList = { 10, 20, 30, 40, 50 };
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
   cout << ' ' << *i;
   //applying clear() function to clear the list
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
      cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出

List before applying clear() function 10 20 30 40 50
list is cleared

示例

在下面的代码中,我们将使用 clear() 函数清空整个列表,然后将新元素重新插入列表并显示相同内容。

 实时演示

#include <iostream>
#include <list>
using namespace std;
int main (){
   list<int> myList;
   std::list<int>::iterator i;
   myList.push_back (10);
   myList.push_back (20);
   myList.push_back (30);
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
      cout << ' ' << *i;
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
   cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   myList.push_back (60);
   myList.push_back (70);
   cout<<"\nelements in my list are: ";
   for (auto i=myList.begin(); i!=myList.end(); ++i)
      cout<< ' ' << *i;
   return 0;
}

如果我们运行以上代码,它将生成以下输出

List before applying clear() function 10 20 30 40 50
list is cleared
Elements in my list are : 60 70

更新时间: 2020年2月26日

4K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.