C++STL---list容器

一、大概含义

list实现了双向链表的数据结构,在链表的任一位置的元素进行插入、删除和查找都是极快速的。同时list的每一个节点有三个域:前驱元素指针域、数据域和后继元素指针域。要注意的是由于list对象的节点并不要求在一段连续的内存中,所以对于迭代器,只能通过++或者--的形式将迭代器移动到后继/前驱的节点元素的位置.

二、用法

 (1)创建list对象

list<int>l;
  //创建了一个空的链表
  list<int>l(10);  
  //创建了具有10个元素的链表

  (2)元素的插入与遍历

#include<list>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
int main()
{
  list<int>l;
  //在list对象的尾部插入数据
  l.push_back(2);
  l.push_back(1);
  l.push_back(5);
  //在list对象的头部插入元素
  l.push_front(8);
   list<int>::iterator it;
   it=l.begin();
   it++;
   l.insert(it,20);//在第二个位置处插入元素
   //使用insert函数在任一位置插入元素
   for(it=l.begin();it!=l.end();it++)
   {
      cout<<*it<<endl;
   }
   //定义反向迭代器
  cout<<"下面是反向迭代的结果"<<endl;
   list<int>::reverse_iterator rit;
   for(rit=l.rbegin();rit!=l.rend();rit++)
   {
   cout<<*rit<<endl;
   }

    return 0;
}

(3)元素的删除

     使用remove()方法删除链表中的元素,值相同的元素都会别删除

    使用pop_front方法删除链表的首元素,pop_back()方法删除链表尾元素。

    使用erase()方法删除迭代器位置上的元素

    使用unique删除连续重复的元素

#include<list>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
int main()
{
  list<int>l;
  //在list对象的尾部插入数据
  l.push_back(2);
  l.push_back(1);
  l.push_back(5);
  l.push_back(11);
  l.push_back(32);
  l.push_back(34);
  l.push_back(1);
  cout<<"下面是没有删除的元素"<<endl;
  list<int>::iterator it;
   for(it=l.begin();it!=l.end();it++)
   {
      cout<<*it<<endl;
   }
   l.remove(1);//删除所有元素等于1
   l.pop_front();//删除队列头部元素
   l.pop_back();//删除队尾元素
   it=l.begin();
   it++;//删除第二个元素
   l.erase(it);//删除迭代器所指向的位置
   cout<<"下面是剩余的元素"<<endl;
   for(it=l.begin();it!=l.end();it++)
   {
      cout<<*it<<endl;
   }
   l.clear();//清空元素

    return 0;
}

(4)元素查找

   通过find()函数在链表中查找元素,如果找到元素,返回的是该元素的迭代器的位置,如果没有找到,返回end()迭代器的位置。

#include<list>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
int main()
{
  list<int>l;
  //在list对象的尾部插入数据
  l.push_back(2);
  l.push_back(1);
  l.push_back(5);
  l.push_back(11);
  l.push_back(32);
  l.push_back(34);
  l.push_back(1);
  list<int>::iterator it;
  for(it=l.begin();it!=l.end();it++)
  {
    cout<<*it<<endl;
  }
  it=find(l.begin(),l.end(),32);//寻找32
  if(it!=l.end())
  {
      cout<<"找到了"<<endl;
  }
  else
  {
    cout<<"没找到"<<endl;
  }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38345598/article/details/86305187