List容器

本文介绍了C++标准库中的List容器,它基于链表实现,支持任意位置的插入和删除操作。文中通过实例展示了list的基本用法,包括push_back、push_front、insert、sort、erase、find等功能,并强调了在list中sort是成员函数而非算法,find则属于算法。此外,还提及了在list中存放自定义类型与存放内建类型相似。
摘要由CSDN通过智能技术生成

list

容器list的底层数据结构为链表,非连续内存,不支持[]操作符,支持任意位置(前后等)操作(push_back/front/insert)。

一个简单实例

#include<iostream>
#include<list>
#include<algorithm>
#include<functional>
using namespace std;
typedef list<char> charlist;
typedef list<char>::iterator charIter;

int main() {
	charlist list;
	charIter it;
	//插入
	for (char c = 'a'; c <= 'z';c++) {
		list.push_back(c);
	}
	//从头部插入
	list.push_front('A');
	list.push_back('B');
	
	//遍历
	for (it = list.begin(); it != list.end();it++) {
		cout << *it << " ";
	}
	cout << endl;

	//从小到大排序
	list.sort(less<int>());
	//遍历
	for (it = list.begin(); it != list.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
	//从大到小排序
	list.sort(greater<int>());
	//遍历
	for (it = list.begin(); it != list.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
	//删除
	for (it = list.begin(); it != list.end();it++) {
		if (*it=='k') {
			it = list.erase(it);
			it--;
		}
	}
	//删除头部
	list.pop_front();
	//删除尾部
	list.pop_back();
	//遍历
	for (it = list.begin(); it != list.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;
	//查找
	it = find(list.begin(),list.end(),'x');
	if (it != list.end()) {
		cout << "found x" << endl;
		//在it位置上插入
		list.insert(it,'X');
	}
	else cout << "not found x" << endl;
	//遍历
	for (it = list.begin(); it != list.end(); it++) {
		cout << *it << " ";
	}
	cout << endl;

}

在这里插入图片描述

注意

  1. 在list中sort()不是一个算法,而是一个成员函数。
  2. find()是算法;
  3. 头文件<list><algonithm><functional>
  4. 断点单步执行(fn F11)整个循环一起执行(fn F5)

在任意位置插入list.insert(it,’ ‘)
list.push_back( )
头部插入 list.push_front(’ ‘);
尾部插入 list.push_back(’ ‘);
list.sort(less())
list.sort(greater());
it = list.erase(it);
头部删除 list.pop_front();
尾部删除list.pop_back();
it = find(list.begin(),list.end(),’ ‘);
list.insert(it,’ ');

存放非内建型别:结构体/类 同vector

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值