当前位置: 首页 > ds >正文

C++ list数据删除、list数据访问、list反转链表、list数据排序

list数据删除,代码见下

#include<iostream>
#include<list>using namespace std;void printList(const list<int>& l) {for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {cout << *it << " ";}cout << endl;
}/*
1 pop_front
2 pop_back
3 erase clear
*/int main() {list<int> l = { -1, 3, 4, 7, 9, -1 };l.pop_back();printList(l);l.pop_front();printList(l);list<int>::iterator it = l.erase(l.begin());printList(l);cout << *it << endl;it = l.erase(it);printList(l);cout << *it << endl;it++;it++;l.erase(it, l.end());printList(l);l.clear();printList(l);cout << "l.size()= " << l.size() << endl;return 0;
}

结果见下,助理解

-1 3 4 7 9
3 4 7 9
4 7 9
4
7 9
7
7 9

l.size()= 0

list数据访问,代码见下

#include<iostream>
#include<list>using namespace std;void printList(const list<int>& l) {for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {cout << *it << " ";}cout << endl;
}int getListItemByIndex(list<int>& l, int index) {list<int>::iterator it = l.begin();while (index) {it++;index--;}return *it;
}int main() {list<int> l = { -1, 2, 1, 3, 4, 7, 9, -1 };list<int>::iterator it = l.begin();cout << getListItemByIndex(l, 4);return 0;
}

list反转列表,代码见下,直接找的内部源码

    void reverse() noexcept { // reverse sequenceconst _Nodeptr _Phead = _Mypair._Myval2._Myhead;_Nodeptr _Pnode       = _Phead;for (;;) { // flip pointers in a nodeconst _Nodeptr _Pnext = _Pnode->_Next;_Pnode->_Next         = _Pnode->_Prev;_Pnode->_Prev         = _Pnext;if (_Pnext == _Phead) {break;}_Pnode = _Pnext;}}

list数据排序,代码见下

#include<iostream>
#include<list>using namespace std;void printList(const list<int>& l) {for (list<int>::const_iterator it = l.begin(); it != l.end(); it++) {cout << *it << " ";}cout << endl;
}int cmp(int a, int b) {return a > b;
}int main() {list<int> l = { 2, 1, 3, 4, 7, 9 };printList(l);l.sort(cmp);printList(l);return 0;
}

http://www.xdnf.cn/news/10405.html

相关文章:

  • HCIE-STP复习
  • C# 密封类和密封方法
  • simulink mask、sfunction和tlc的联动、接口
  • CSS专题之层叠上下文
  • 小明的Java面试奇遇之:支付平台高并发交易系统设计与优化[特殊字符]
  • [SC]SystemC在CPU/GPU验证中的应用(三)
  • 【2025年软考中级】第二章 2.1 程序设计语言的基本概念
  • 【C语言】讲解 程序分配的区域(新手)
  • 论文笔记: Urban Region Embedding via Multi-View Contrastive Prediction
  • C#数字图像处理(一)
  • 【Hot 100】55. 跳跃游戏
  • Unity3D仿星露谷物语开发57之保存库存信息到文件
  • ROS2与Unitree机器人集成指南
  • Linux 基础IO(上)
  • javaweb-maven以及http协议
  • (LeetCode 每日一题) 909. 蛇梯棋 (广度优先搜索bfs)
  • 电子电器架构 --- OTA测试用例分析(上)
  • 华为OD机试_2025 B卷_小明减肥(Python,100分)(附详细解题思路)
  • 最卸载器——Geek Uninstaller 使用指南
  • 设备健康管理的战略升维:用预测性维护重构企业竞争力
  • JDK21深度解密 Day 9:响应式编程模型重构
  • 性能优化 - 理论篇:CPU、内存、I/O诊断手段
  • 性能优化 - 理论篇:常见指标及切入点
  • 钉钉红包性能优化之路
  • Git入门到精通:30分钟掌握核心技巧
  • 第二章支线三 ·《CSS炼金术:动画与变换高级奥义》
  • C++文件和流基础
  • [蓝桥杯]春晚魔术【算法赛】
  • Socket编程之TCP套件字
  • 深 入 剖 析 单 链 表:从 原 理 到 实 战 应 用