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

list数据删除,代码见下

cpp 复制代码
#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数据访问,代码见下

cpp 复制代码
#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反转列表,代码见下,直接找的内部源码

cpp 复制代码
    void reverse() noexcept { // reverse sequence
        const _Nodeptr _Phead = _Mypair._Myval2._Myhead;
        _Nodeptr _Pnode       = _Phead;

        for (;;) { // flip pointers in a node
            const _Nodeptr _Pnext = _Pnode->_Next;
            _Pnode->_Next         = _Pnode->_Prev;
            _Pnode->_Prev         = _Pnext;

            if (_Pnext == _Phead) {
                break;
            }

            _Pnode = _Pnext;
        }
    }

list数据排序,代码见下

cpp 复制代码
#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;
}
相关推荐
chenyuhao20248 分钟前
vector深度求索(上)实用篇
开发语言·数据结构·c++·后端·算法·类和对象
江公望13 分钟前
Qt中,Latin-1字符编码简介
开发语言·arm开发·qt
温启志c#18 分钟前
winform c# 做的2个运控平台,通过修改表格 的方式,也可以通过语音识别的交互方式,更加智能。
开发语言·c#
花心蝴蝶.1 小时前
JVM 内存结构
java·开发语言·jvm
97zz1 小时前
实战排查:Java 解析 Excel 大型 导致内存溢出问题的完整解决过程
java·开发语言·spring boot·excel
小小测试开发1 小时前
Python + MediaPipe 手势绘画高级应用:从基础到创意交互
开发语言·python·交互
会跑的葫芦怪1 小时前
Go tool pprof 与 Gin 框架性能分析完整指南
开发语言·golang·gin
爱学习的小道长2 小时前
Python调用优云智算安装的ComfyUI服务器
服务器·开发语言·python
什么半岛铁盒2 小时前
C++项目:仿muduo库高并发服务器------EventLoop模块的设计
linux·服务器·c++·mysql·ubuntu
要做朋鱼燕2 小时前
解析UART空闲中断与DMA接收机制
开发语言·笔记·单片机·嵌入式硬件·rtos·嵌入式软件