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;
}
相关推荐
wb18918 分钟前
shell脚本的条件测试
开发语言·python·excel
STY_fish_20121 小时前
手拆STL
java·c++·算法
孞㐑¥1 小时前
Linux之进程间通信
linux·c++·经验分享·笔记
kukubuzai1 小时前
c++继承
c++·学习
埃伊蟹黄面1 小时前
C++ —— STL容器——string类
c++
pumpkin845144 小时前
Rust Mock 工具
开发语言·rust
love530love4 小时前
【笔记】在 MSYS2(MINGW64)中安装 python-maturin 的记录
运维·开发语言·人工智能·windows·笔记·python
阿卡蒂奥5 小时前
C# 结合PaddleOCRSharp搭建Http网络服务
开发语言·http·c#
kingmax542120085 小时前
【洛谷P9303题解】AC- [CCC 2023 J5] CCC Word Hunt
数据结构·c++·算法·广度优先
泉飒7 小时前
lua注意事项
开发语言·笔记·lua