list容器在数组中的使用

2020-05-06  本文已影响0人  与时间共舞

List容器的存储结构

  1. list容器底层是链表结构,内存不连续,不能使用[]运算符操作
  2. vector是数组维护的,拥有连续的内存,可以使用[]运算符操作
  3. list对比vector添加了新的方法,因为底层是链表,所以可以对头尾进行删除或者添加元素
#include <iostream>
#include <list> 
using namespace std;
int main(){
    //创建list容器
    list<int> lst;
    //在容器中添加n个元素
    int a,n;
    cin>>n;
    for(int i=0; i<n; i++){
        cin>>a;
        //将输入的数值存放到lst容器中
        lst.push_back(a);  
    } 

    //迭代list容器
    list<int>::iterator it = lst.begin();
    for(it; it!=lst.end(); ++it){
        //不能使用[]访问,it其实是个指针对象
        cout<<(*it)<<endl;   
    } 
    
    //队尾添加元素
    cout<<"请输入队尾要添加的元素:"<<endl;
    cin>>a;
    lst.push_back(a); 
    //对头添加元素 
    cout<<"请输入队头要添加的元素:"<<endl;
    cin>>a; 
    lst.push_front(a);
    //遍历list容器打印其中的元素
    it = lst.begin();
    for(it; it!=lst.end(); ++it){
        cout<<(*it)<<" ";   
    }  
    //删除元素 -- 删除第二个元素 
    it = ++lst.begin();
    lst.erase(it);  //删除指定元素
    lst.pop_back(); //从尾部删除元素
    lst.pop_front();//从头部删除元素 
    //遍历list容器打印其中的元素
    it = lst.begin();
    for(it; it!=lst.end(); ++it){
        cout<<(*it)<<" ";   
    }  
    
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读