c++中的链表list

前言

c++里面的list容器,真的是链表实现,中间元素的插入和删除是 O ( 1 ) O(1) O(1) 时间复杂度的。有必要了解一下它的基本用法。

代码

cpp 复制代码
#include <list>
#include <iostream>


using namespace std;


int main()
{
    list<int> lst{1,3,4,2};
    auto it  = lst.begin();
    it++;

    // 插入元素
    lst.insert(it, {20,30,40}); // 插入到第2个位置
    for(auto item : lst) cout << item << " "; cout << endl; /*[ 1 20 30 40 3 4 2 ]*/

    // 按位置删除元素
    it =  lst.begin();
    advance(it, 1); // 删除第2个元素
    lst.erase(it); 
    for(auto item : lst) cout << item << " "; cout << endl; /*[ 1 30 40 3 4 2 ]*/


    // 按值删除元素
    lst.remove(2); // 删除所有为2的元素
    for(auto item : lst) cout << item << " "; cout << endl; /*[ 1 30 40 3 4 ]*/


    return 0;
}

结果

复制代码
1 20 30 40 3 4 2 
1 30 40 3 4 2
1 30 40 3 4
相关推荐
端平入洛20 小时前
auto有时不auto
c++
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx2 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX2 天前
020-C++之unordered容器
数据结构·c++
会编程的土豆2 天前
2.25 做题
数据结构·c++·算法