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
相关推荐
cookies_s_s1 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
不想编程小谭2 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
曼巴UE53 小时前
UE5.3 C++ TArray系列(一)
开发语言·c++·ue5
阿巴~阿巴~3 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
CoderCodingNo4 小时前
【GESP】C++二级真题 luogu-b3924, [GESP202312 二级] 小杨的H字矩阵
java·c++·矩阵
刃神太酷啦5 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组
Heris995 小时前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----5 小时前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++
ChoSeitaku6 小时前
12.重复内容去重|添加日志|部署服务到Linux上(C++)
linux·c++·windows
挣扎与觉醒中的技术人6 小时前
网络安全入门持续学习与进阶路径(一)
网络·c++·学习·程序人生·安全·web安全