c++(list)

目录

迭代器

 sort(随机迭代器)​编辑

list(双向迭代器)

vector(随记迭代器)

find(input迭代器--只读--可传任意类型迭代器)

​编辑 尾插        push_back/emplace_back

插入数据        

删除

交换(swap)

 排序

链表合并(merge) 

 删除(remove)

剪切(splice)

去重(unique)

sort

底层实现

push_back();

迭代器

list链表

insert

erase

pop_back/pop_front

解释

 const_iterator和iterator

改进:一个类模板实现两个类 

 迭代器失效-----insert不失效,erase不失效

erase需要更新迭代器

析构

拷贝构造

赋值重载

std::initializer_list

单独支持一个构造函数


迭代器

功能:
iterator
reverse_iterator
const_iterator
const_reverse_iterator

 性质:
单向:forward_list/unordered_map...                              ++
双向:list/map/set(二叉树结构)...                                    ++/--
随机:vector/string/deque(连续的物理空间)..                 ++/--/+/-

底层结构----决定使用哪些算法
内存是否连续只能决定随机,但不能判断单双向

 sort(随机迭代器)

list(双向迭代器)

vector(随记迭代器)

find(input迭代器--只读--可传任意类型迭代器)

 

 尾插        push_back/emplace_back

插入数据        

list<int> lt;
auto it=lt.begin();
int k=3;
while(k--)
{++it;}
lt.insert(it,30);

删除

it=find(lt.begin(),lt.end(),x);
if(it!=lt.end())
{lt.erase(it);}

交换(swap)

两个链表交换,不走深拷贝,直接交换头指针

 排序

less<int> ls;//升序
greater<int>gt;//降序
lt.sort(gt);
lt.sort(greater<int>());//匿名对象

链表合并(merge) 

 链表合并(前提:两个链表有序)取小尾插

被合并的链表合并之后为空

 // 合并两个链表list1.merge(list2);List 1: 1 3 5 7 
List 2: 2 4 6 8 
Merged List: 1 2 3 4 5 6 7 8 
List 2 after merge (should be empty): 

 删除(remove)

剪切(splice)

一个链表的节点转移到该链表某一位置

// 一个链表节点转移给另一个链表std::list<int> mylist1, mylist2;std::list<int>::iterator it;// set some initial values:for (int i = 1; i <= 4; ++i)mylist1.push_back(i);      // mylist1: 1 2 3 4for (int i = 1; i <= 3; ++i)mylist2.push_back(i * 10);   // mylist2: 10 20 30it = mylist1.begin();++it;                         // points to 2mylist1.splice(it, mylist2); // mylist1: 1 10 20 30 2 3 4// mylist2 (empty)// "it" still points to 2 (the 5th element
// 调整当前链表节点的顺序list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);lt.push_back(5);lt.push_back(6);for (auto e : lt){cout << e << " ";}cout << endl;int x = 0;cin >> x;it = find(lt.begin(), lt.end(), x);if (it != lt.end()){//lt.splice(lt.begin(), lt, it);lt.splice(lt.begin(), lt, it, lt.end());}for (auto e : lt){cout << e << " ";}cout << endl;

去重(unique)

sort

算法库的sort             快排(递归)debug版本下较差
list的sort               适合少量数据的排序

底层实现

template<class T>struct list_node{public:T _data;list_node<T>* _next;list_node<T>* _prev;};template<class T>class list{typedef list_node<T> Node;public:list(){_head=new Node;_head->next=_head;_head->prev=_head;_size = 0;}private:Node* _head;size_t _size;};

push_back();

void push_back(const T& x){Node* newnode = new Node(x);Node* tail = _head->_prev;tail->_next = newnode;newnode->_prev = tail;newnode->_next = _head;_head->_prev = newnode;}

迭代器

// const_iteratortemplate<class T>struct list_iterator{typedef list_node<T> Node;typedef list_iterator<T> Self;Node* _node;list_iterator(Node* node):_node(node){}T& operator*(){return _node->_data;}Self& operator++(){_node = _node->_next;return *this;}Self& operator--(){_node = _node->_prev;return *this;}bool operator!=(const Self& s) const{return _node != s._node;}bool operator==(const Self& s) const{return _node == s._node;}};

list链表

template<class T>class list{typedef list_node<T> Node;public:typedef list_iterator<T> iterator;iterator begin(){/*	iterator it(_head->_next);return it;*///return iterator(_head->_next);return _head->_next;//返回节点的指针,接收的是iterator,节点的指针隐式类型转换为iterator}iterator end()//最后一个位置的下一个数据{return _head;}list(){_head = new Node;_head->_next = _head;_head->_prev = _head;_size = 0;}void push_back(const T& x){/*Node* newnode = new Node(x);Node* tail = _head->_prev;tail->_next = newnode;newnode->_prev = tail;newnode->_next = _head;_head->_prev = newnode;++_size;*/insert(end(), x);}void push_front(const T& x){insert(begin(), x);}void insert(iterator pos, const T& x){Node* cur = pos._node;Node* prev = cur->_prev;Node* newnode = new Node(x);// prev newnode curnewnode->_next = cur;cur->_prev = newnode;newnode->_prev = prev;prev->_next = newnode;++_size;}void pop_back(){erase(--end());}void pop_front(){erase(begin());}void erase(iterator pos){assert(pos != end());Node* prev = pos._node->_prev;Node* next = pos._node->_next;prev->_next = next;next->_prev = prev;delete pos._node;--_size;}size_t size() const{return _size;}bool empty() const{return _size == 0;}private:Node* _head;size_t _size;};

insert

void insert(iterator pos, const T& x){Node* cur = pos._node;Node* prev = cur->_prev;Node* newnode = new Node(x);// prev newnode curnewnode->_next = cur;cur->_prev = newnode;newnode->_prev = prev;prev->_next = newnode;++_size;}

erase

void erase(iterator pos){assert(pos != end());Node* prev = pos._node->_prev;Node* next = pos._node->_next;prev->_next = next;next->_prev = prev;delete pos._node;--_size;}

pop_back/pop_front

void pop_back(){erase(--end());}void pop_front(){erase(begin());}

ita 是一个迭代器,ita.operator->() 返回一个指向当前节点的指针。由于 ita 是 list_iterator 类型的对象,它本身并不直接包含 _a1 和 _a2 成员。相反,它指向一个 list_node<AA> 对象,该对象包含 _data,而 _data 是 AA 类型的对象。

解释

  1. 解引用操作

    • *ita 会返回一个 AA 对象(即当前节点的数据),然后你可以使用 (*ita)._a1 和 (*ita)._a2 访问其成员。
    • 这种方式是完全合法的,但在语法上稍显冗长。
  2. 箭头操作

    • ita-> 实际上是等价于 (*ita).operator->(),它返回指向 AA 对象的指针,因此你可以直接访问 _a1 和 _a2
	list<AA> lta;lta.push_back(AA());lta.push_back(AA());lta.push_back(AA());lta.push_back(AA());list<AA>::iterator ita = lta.begin();while (ita != lta.end()){//cout << (*ita)._a1 << ":" << (*ita)._a2 << endl;// 特殊处理,本来应该是两个->才合理,为了可读性,省略了一个->cout << ita->_a1 << ":" << ita->_a2 << endl;cout << ita.operator->()->_a1 << ":" << ita.operator->()->_a2 << endl;++ita;}cout << endl;T* operator->(){return &_node->_data;}

cout << *ita;
如果你想直接打印 *ita,需要确保 AA 类型重载了 operator<<。否则,编译器将不知道如何打印 AA 的对象。 

#include <iostream>struct AA {int _a1 = 1;int _a2 = 1;// 重载 operator<<friend std::ostream& operator<<(std::ostream& os, const AA& obj) {os << obj._a1 << ":" << obj._a2;return os;}
};

 const_iterator和iterator

operator*和operator->   都不能修改

template<class Container>void print_container(const Container& con){// const iterator -> 迭代器本身不能修改// const_iterator -> 指向内容不能修改typename Container::const_iterator it = con.begin();//auto it = con.begin();while (it != con.end()){//*it += 10;cout << *it << " ";++it;}cout << endl;for (auto e : con){cout << e << " ";}cout << endl;}

 

按需实例化 ------- 没有实例化对象,不会检查出来错误

改进:一个类模板实现两个类 

template<class T, class Ref, class Ptr>struct list_iterator{typedef list_node<T> Node;typedef list_iterator<T, Ref, Ptr> Self;Node* _node;list_iterator(Node* node):_node(node){}Ref operator*(){return _node->_data;}Ptr operator->(){return &_node->_data;}Self& operator++(){_node = _node->_next;return *this;}Self& operator--(){_node = _node->_prev;return *this;}Self operator++(int){Self tmp(*this);_node = _node->_next;return tmp;}Self& operator--(int){Self tmp(*this);_node = _node->_prev;return tmp;}bool operator!=(const Self& s) const{return _node != s._node;}bool operator==(const Self& s) const{return _node == s._node;}};

 迭代器失效-----insert不失效,erase不失效

list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4);// insert以后迭代器不失效list<int>::iterator it = lt.begin();lt.insert(it, 10);*it += 100;print_container(lt);// erase以后迭代器失效// 删除所有的偶数it = lt.begin();while (it != lt.end()){if (*it % 2 == 0){it = lt.erase(it);}else{++it;}}print_container(lt);

erase需要更新迭代器

iterator erase(iterator pos){assert(pos != end());Node* prev = pos._node->_prev;Node* next = pos._node->_next;prev->_next = next;next->_prev = prev;delete pos._node;--_size;return next;}

析构

~list(){clear();delete _head;_head = nullptr;}void clear(){auto it = begin();while (it != end()){it = erase(it);}}

拷贝构造

void empty_init(){_head = new Node;_head->_next = _head;_head->_prev = _head;_size = 0;}list(){empty_init();}list(initializer_list<T> il){empty_init();for (auto& e : il){push_back(e);}}

赋值重载

// lt1 = lt3list<T>& operator=(list<T> lt){swap(lt);return *this;}
void swap(list<T>& lt){std::swap(_head, lt._head);std::swap(_size, lt._size);}

std::initializer_list

单独支持一个构造函数

list(initializer_list<T> il){empty_init();for (auto& e : il){push_back(e);}}
void func(const list<int>& lt){print_container(lt);}void test_list4(){// 直接构造list<int> lt0({ 1,2,3,4,5,6 });// 隐式类型转换list<int> lt1 = { 1,2,3,4,5,6,7,8 };const list<int>& lt3 = { 1,2,3,4,5,6,7,8 };func(lt0);func({ 1,2,3,4,5,6 });print_container(lt1);//auto il = { 10, 20, 30 };/*	initializer_list<int> il = { 10, 20, 30 };cout << typeid(il).name() << endl;cout << sizeof(il) << endl;*/}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1522913.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Opencv中的直方图(3)直方图比较函数compareHist()的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 比较两个直方图。 函数 cv::compareHist 使用指定的方法比较两个密集或两个稀疏直方图。 该函数返回 d ( H 1 , H 2 ) d(H_1, H_2) d(H1​,H2​…

巧用xrename批量重命名下载的影视文件

网上下载了个电视剧&#xff0c;可是文件名比较长&#xff0c;而且是集数用中文表示的&#xff0c;排序都是乱的。期望的是&#xff1a; 1.文件名改短 2.中文的数字改成阿拉伯数字 看下原始文件名&#xff1a; 期望将文件名改短&#xff0c;例如&#xff1a; 修改前&#xff…

Golang环境安装、配置详细

Windows下安装Go开发环境 点我下载 Windows配置Go环境变量 出现工具install失败时&#xff0c;切换其它代理 # 1. 七牛 CDN go env -w GOPROXYhttps://goproxy.cn,direct# 2. 阿里云 go env -w GOPROXYhttps://mirrors.aliyun.com/goproxy/,direct# 3. 官方 go env -w GOP…

硬件工程师笔试面试知识器件篇——电阻

目录 1、电阻 1.1 基础 电阻原理图 阻实物图 1.1.1、定义 1.1.2、工作原理 1.1.3、类型 1.1.4、材料 1.1.5、标记 1.1.6、应用 1.1.7、特性 1.1.8、测量 1.1.9、计算 1.1.10、颜色编码 1.1.11、公差 1.1.12、功率 1.1.13、重要性 1.2、相关问题 1.2.1、电阻…

电路分析 ---- 同相比例放大器和电压跟随器

1 同相比例运算放大器 同相比例运算放大电路引入了电压串联负反馈&#xff0c;故可以认为输入电阻无穷大&#xff0c;输出电阻为0 分析过程 虚短&#xff0c; u N u P u I u_{N}u_{P}u_{I} uN​uP​uI​ i F i R → u o − u N R f u N − 0 R → u o − u I R f u I R i…

【前端面试】leetcode指针解法javascript

最大盛水 https://leetcode.cn/problems/container-with-most-water/ var maxArea = function(height) {// 左右指针靠拢let left = 0;let right = height.length-1;let maxArea = 0; while(left<right){// 计算出 当前的容积 与最大容积比较,取出最大的const currentAre…

算法数学加油站:一元高斯分布(正态分布)Python精美科研绘图(PDF、CDF、PPF、ECDF曲线;QQ图)

这类博客针对算法学习时可能遇到的数学知识补充&#xff0c;但不会太多废话&#xff0c;主要是公式结合Python代码精美绘图理解&#xff01; 本期重点&#xff1a; 参数&#xff1a;期望、标准差曲线&#xff1a;概率密度曲线PDF、累积概率密度函数CDF、百分点函数PPF应用&am…

【Webpack】基本使用方法

参考视频&#xff1a; 30 分钟掌握 Webpack_哔哩哔哩_bilibili 什么是webpack 简单来说就是一个 打包工具&#xff0c; 可以将互相依赖的html、css、js以及图片字体等资源文件&#xff0c;经过处理打包成一个可执行的项目文件 &#x1f330;看例子 环境初始化 在需要使用…

C语言 09 流程控制

if 如果需要判断某个条件&#xff0c;当满足此条件时&#xff0c;才执行某些代码&#xff0c;那这个时候该怎么办呢&#xff1f;可以使用if语句来实现&#xff1a; #include <stdio.h>int main() {int i 0;// 只希望i大于10的时候才执行下面的打印语句if (i > 10) …

YUM配置文件开启缓存

可设置一台服务器或者云主机作为外网YUM源&#xff0c;并且开启yum在线下载缓存&#xff0c;之后可将服务器所有安装包缓存同步到内网本地。 # vim /etc/yum.conf 将 “keepcache0” 改为 “keepcache1” 缓存目录为 /var/cache/yum/xxx/xxx/xxx 日后可下载到本地然后上传到…

024集—— 正则表达式、replace、DateTime日期的用法——C#学习笔记

DateTime 是一个struct结构体。 代码如下&#xff1a; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ConsoleApp1 {internal class Program{static void Main(string[] args){args new s…

HNU OS实验六

本内容针对湖南大学特色os实验前言 — os2024 lab 文档

ubuntu驱动掉了,重装nvidia驱动

跑深度学习&#xff0c;忽然发现显卡驱动掉了 主要根据这篇文章&#xff1a;[超级详细系列]ubuntu22.04配置深度学习环境(显卡驱动CUDAcuDNNPytorch)--[1]安装显卡驱动_ubuntu22 cuda cudnn pytorch-CSDN博客 用里面的在线安装方法不行&#xff0c;换成用2.2 离线安装方法。从…

动态路由和路由导航守卫及其案例分析

为什么需要动态路由&#xff1f; 动态路由其实用的不多&#xff0c;在实际开发中&#xff0c;如果遇到权限分配问题&#xff0c;比如对于一个公司人员的后台管理系统&#xff0c;那对不同成员的权限肯定不同&#xff0c;对于人事部&#xff0c;他们有权限进入成员表对人员的流…

云计算实训41——部署project_exam_system项目(续)

# 创建脚本&#xff0c;可以在java环境中运行任何的jar包或者war包#!/bin/bash/usr/local/jdk/bin/java -jar /java/src/*.?ar一、思路分析 &#xff08;1&#xff09;nginx 1、下载镜像&#xff0c;将本地的dist项目的目录挂载在容器的/usr/share/nginx/html/ 2、启动容器 …

性能工具之 JMeter ajax 简单登录案例实战

文章目录 一、前言二、前置工作三、登陆密码分析四、JMeter脚本开发四、登陆性能分析五、小结 一、前言 想起论语中的 “学而时习之不亦说乎” &#xff0c;也想找个开源项目实战一把&#xff0c;下面用一个开源ERP系统中的登陆做今天的实战。 二、前置工作 开源ERP项目地址…

getLocation:fail, the permission value is offline verifying

getLocation:fail, the permission value is offline verifying 后端会根据appid和secret生成 签名&#xff0c;前端wx配置时一定用appid来验证签名的正确 本次错误为配置初始化失败&#xff1a;前端与后端的appId不一致&#xff0c;我的失误也

IP 协议详解

一、认识 IP 地址与网络层的职责 网络层是OSI七层模型中的第三层&#xff0c;也是TCP/IP四层模型中的网络接入层。在这一层&#xff0c;数据包被封装并加上IP层的头部信息&#xff0c;以便在网络之间传输。网络层的主要功能包括路由选择、分段与重组、拥塞控制以及IP地址管理等…

stm32的内部时钟源 | RC震荡电路

文章目录 前言学习了解 前言 了解到 内部高速RC振荡器&#xff08;HSI&#xff09;就是RC震荡器实现的&#xff0c;故想对RC震荡做些了解与分析。 学习了解 【不需要晶振&#xff0c;也可产生时钟脉冲&#xff01;RC振荡器的工作原理&#xff0c;维恩电桥振荡器&#xff01;…

Mental-LLM——通过在线文本数据利用大型语言模型进行心理健康预测

概述 源码地址&#xff1a;https://github.com/neuhai/Mental-LLM.git 论文地址&#xff1a;https://arxiv.org/abs/2307.14385 在一项关于哪些法律硕士适合精神健康护理的研究中&#xff0c;对以下五种法律硕士进行了比较 羊驼-7b。羊驼-LoRA。FLAN-T5-XXLGPT-3.5GPT-4. 作…