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;
}
相关推荐
workflower1 天前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
YuanlongWang1 天前
C# 基础——装箱和拆箱
java·开发语言·c#
b78gb1 天前
电商秒杀系统设计 Java+MySQL实现高并发库存管理与订单处理
java·开发语言·mysql
LXS_3571 天前
Day 05 C++ 入门 之 指针
开发语言·c++·笔记·学习方法·改行学it
etsuyou1 天前
js前端this指向规则
开发语言·前端·javascript
shizhenshide1 天前
为什么有时候 reCAPTCHA 通过率偏低,常见原因有哪些
开发语言·php·验证码·captcha·recaptcha·ezcaptcha
挂科是不可能出现的1 天前
最长连续序列
数据结构·c++·算法
_Aaron___1 天前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
mit6.8241 天前
[Agent可视化] 配置系统 | 实现AI模型切换 | 热重载机制 | fsnotify库(go)
开发语言·人工智能·golang
友友马1 天前
『 QT 』QT控件属性全解析 (一)
开发语言·前端·qt