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;
}
相关推荐
新手小新2 小时前
C++游戏开发(2)
开发语言·前端·c++
你的电影很有趣3 小时前
lesson30:Python迭代三剑客:可迭代对象、迭代器与生成器深度解析
开发语言·python
程序员编程指南4 小时前
Qt 嵌入式界面优化技术
c语言·开发语言·c++·qt
q__y__L5 小时前
C#线程同步(二)锁
开发语言·性能优化·c#
二川bro5 小时前
第二篇:Three.js核心三要素:场景、相机、渲染器
开发语言·javascript·数码相机
云泽8085 小时前
数据结构前篇 - 深入解析数据结构之复杂度
c语言·开发语言·数据结构
逝雪Yuki5 小时前
数据结构与算法——字典(前缀)树的实现
数据结构·c++·字典树·前缀树·左程云
卷卷的小趴菜学编程5 小时前
Qt-----初识
开发语言·c++·qt·sdk·qt介绍
天天进步20156 小时前
Python游戏开发引擎设计与实现
开发语言·python·pygame
Vic101016 小时前
Hutool 的完整 JSON 工具类示例
开发语言·json