list使用及模拟

发布于:2025-06-16 ⋅ 阅读:(19) ⋅ 点赞:(0)

01. list介绍

  1. list是支持常数时间内任意位置插入删除的序列容器,具备双向迭代能力。
  2. 其底层为双向链表结构,各元素存于独立节点,通过指针指向前后元素。
  3. 与forward_list的主要区别:后者是单链表,仅支持单向迭代,结构更简单高效。
  4. 相比array、vector、deque等序列容器,list在任意位置插入/删除元素的效率更优。
  5. 缺陷:不支持随机访问(如访问第6个元素需线性迭代),且因节点存储额外信息,对存储小元素的大列表可能更占空间。

在这里插入图片描述


02. list使用

2.1 list构造器

在这里插入图片描述

void printlist(const list<int>&li,const string&name){
   
    cout << name << " ";
   list<int> tmp = li;
    if(tmp.empty()){
   //不空往下走
        cout << "empty" << endl;
        return ;
    }
        while (!tmp.empty()){
   
            cout << tmp.front() << " ";
            tmp.pop_front();
        }
    cout << endl;
}
int main()
{
   
    list<int> l1(2, 5);
    list<int> l2;
    list<int> l3(l1);
    list<int> l4(l1.begin(), l1.end());
    printlist(l1, "l1:");
    printlist(l2, "l2:");
    printlist(l3, "l3:");
    printlist(l4, "l4:");
    system("pause");
    return 0;
}

2.2 list迭代器

int main()
{
   
    list<int> l1;
    l1.push_back(1);
    l1.push_back(2);
    l1.push_back(3);
    l1.push_back(4);
    list<int>::iterator it = l1.begin();
    while (it!=l1.end()){
   
        cout << *it << "  ";
        it++;
    }cout << endl;
    list<int>::reverse_iterator rit = l1.rbegin();
    while (rit!=l1.rend()){
   
        cout << *rit << "  ";
        rit++;
    }

2.3 元素访问接口
函数声明 接口说明
front() 返回链表首元素的引用
back() 返回链表尾元素的引用

网站公告

今日签到

点亮在社区的每一天
去签到