list容器

介绍

list容器与双向链表


用途

快速插入删除


头文件以及构造方法

#include <list>

using namespace std;

int main(){
    list<int> l;
    

插入数据以及遍历

int main(){
    list<int> l;
    
    for (int i = 0; i < 3; i ++ ) l.push_back(i + 1);
    
    list<int>::iterator iter;
    for (iter = l.begin(); iter != l.end(); iter ++)
    cout << *iter << ' ';
    
    return 0;
}

list函数

插入

从末端插入元素[push_back()]

从头部插入元素[push_front()]

    l.push_back(1);
    l.push_back(2);
    l.push_front(3);
    l.push_front(4);
    
    list<int>::iterator iter;
    for (iter = l.begin(); iter != l.end(); iter ++)
    cout << *iter << ' ';
    //4 3 1 2 

获取头部元素[front()]与尾部元素[back()]

    list<int> l;
    
    l.push_back(1);
    l.push_back(2);
    l.push_front(3);
    l.push_front(4);
    //4 3 1 2
    cout << l.front() << endl;//4
    cout << l.back() << endl;//2

删除最后一个元素[pop_back()]与删除第一个元素[pop_front()]

    list<int> l;
    
    l.push_back(1);
    l.push_back(2);
    l.push_front(3);
    l.push_front(4);
    //4 3 1 2
    l.pop_back();//4 3 1 
    //l.pop_front();//4 3 1 

判断是否为空[empty()]

    list<int> l;
    
    l.push_back(1);
    l.push_back(2);
    l.push_front(3);
    l.push_front(4);
    
    if (l.empty()) puts("Yes");
    else puts("No");

清空list内的所有元素[clear()]


插入一个元素或多个元素[insert()]


删除一个元素或一个区间[erase()]


补充

插入下标为x的后面

    list<int> l;
    l.push_back(1);
    l.push_back(2);
    l.push_front(3);
    l.push_front(4);
    //4 3 1 2
    //插入下标为2的后面
    int i = 0;
    list<int>::iterator it = l.begin();
    while (it != l.end() && i <= 2){
        ++ it;
        ++ i;
    }
    //4 3 1 7 2 
    l.insert(it, 7);

其他

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值