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;
}
相关推荐
周一上线5 分钟前
EDA 中的 DRC检测——并查集优化mincut规则检测
c++·eda·经验·工艺
embrace9920 分钟前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
无心水22 分钟前
【Python实战进阶】4、Python字典与集合深度解析
开发语言·人工智能·python·python字典·python集合·python实战进阶·python工业化实战进阶
代码不停37 分钟前
Java单链表和哈希表题目练习
java·开发语言·散列表
Dxxyyyy39 分钟前
零基础学JAVA--Day37(坦克大战1.0)
java·开发语言
u***u6851 小时前
PHP在电商中的WooCommerce
开发语言·php
冠希陈、1 小时前
PHP 过滤敏感词(含类库)
开发语言·php·内容敏感词
qq_401700411 小时前
Qt Positioning 模块访问设备地理位置信息
开发语言·qt
1***s6321 小时前
C++移动语义优化
开发语言·c++
m5655bj2 小时前
使用 Python 高效复制 Excel 行、列、单元格
开发语言·python·excel