stl_list

发布于:2024-04-26 ⋅ 阅读:(26) ⋅ 点赞:(0)

list

1. list的介绍及使用

1.1 list的介绍

list文档介绍

  1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。

  2. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。

  3. list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。

  4. 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率更好。

  5. 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这可能是一个重要的因素)。

在这里插入图片描述

1.2 list的接口

list中的接口比较多,此处类似,只需要掌握如何正确的使用,然后再去深入研究背后的原理,已达到可扩展的能力。以下为list中一些常见的重要接口

1.2.1 list的构造
构造函数( (constructor) 接口说明
list (size_type n, const value_type& val = value_type()) 构造的list中包含n个值为val的元素
list() 构造空的list
list (const list& x) 拷贝构造函数
list (InputIterator first, InputIterator last) 用[first, last)区间中的元素构造list
1.2.2 list iterator的使用

此处,大家可暂时 将迭代器理解成一个指针,该指针指向list中的某个节点

函数声明 接口说明
begin + end 返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器
rbegin + rend 返回第一个元素的reverse_iterator,即end位置,返回最后一个元素下一个位置的reverse_iterator,即begin位置

在这里插入图片描述

【注意】

  1. beginend 为正向迭代器,对迭代器执行 ++ 操作,迭代器向后移动

  2. **rbegin(end) **与 rend(begin) 为反向迭代器,对迭代器执行 **++ **操作,迭代器向前移动

1.2.3 list capacity
函数声明 接口说明
empty 检测list是否为空,是返回true,否则返回false
size 返回list中有效节点的个数
1.2.4 list element access
函数声明 接口说明
front 返回list的第一个节点中值的引用
back 返回list的最后一个节点中值的引用
1.2.5 list modifiers
函数声明 接口说明
push_front 在list首元素前插入值为val的元素
pop_front 删除list中第一个元素
push_back 在list尾部插入值为val的元素
pop_back 删除list中最后一个元素
insert 在list position 位置中插入值为val的元素
erase 删除list position位置的元素
swap 交换两个list中的元素
clear 清空list中的有效元素

list中还有一些操作,需要用到时大家可参阅list的文档说明。

1.2.6 list的迭代器失效

前面说过,此处大家可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此list中进行插入时是不会导致list的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响

void func()
{
    int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));
    auto it = l.begin();
    while (it != l.end())
    {
        // erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
        l.erase(it);
        ++it;
    }
}

// 改正
void func()
{
    int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));
    auto it = l.begin();
    while (it != l.end())
    {
        l.erase(it++); // it = l.erase(it);
    }
}

2. list接口实现

2.1 push_back

示例:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> It;
    It.push_back(1);
    It.push_back(2);
    It.push_back(3);
    It.push_back(4);
    It.push_back(5);

    list<int>::iterator it = It.begin();
    while(it != It.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    for(auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

list既然遵循迭代器,那也必然可以使用范围for。

示例结果:

在这里插入图片描述

2.2 reverse

reverse表示链表的逆置。

示例:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> It;
    It.push_back(1);
    It.push_back(2);
    It.push_back(3);
    It.push_back(4);
    It.push_back(5);

    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;

    It.reverse();  //链表逆置

    for(auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

演示结果:

在这里插入图片描述

2.3 sort

sort接口默认是升序排序。

示例:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> It;
    It.push_back(1);
    It.push_back(2);
    It.push_back(3);
    It.push_back(4);
    It.push_back(5);

    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;

    It.reverse(); 
    for(auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;

    It.sort();
    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

演示结果:

在这里插入图片描述

当然sort也可以在迭代器范围之间排序:sort( It.begin() , It.end() )

如果想降序排序,需要用到一个仿函数greater。

降序排序:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> It;
    It.push_back(1);
    It.push_back(2);
    It.push_back(3);
    It.push_back(4);
    It.push_back(5);

    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;

    greater<int> gt;
    It.sort(gt);  //两句可以合并写为: It.sort(greater<int>());
    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

降序结果:

在这里插入图片描述

2.4 remove

remove可以直接删除指定的数值。

示例:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> It;
    It.push_back(1);
    It.push_back(3);
    It.push_back(2);
    It.push_back(3);
    It.push_back(4);
    It.push_back(3);
    It.push_back(5);
    It.push_back(3);

    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;

   
    It.remove(3);
    for (auto e : It)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

演示结果:

在这里插入图片描述

可以看到,remove可以删除所有指定的值,包括重复的数值。

如果remove一个不存在的数值,则没有任何反应,程序正常执行后续代码。

2.5 splice

splice指转移,可以将一个链表的值转移到另一个链表里。

示例:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> mylist1, mylist2;
    list<int>::iterator it;

    for(int i = 1; i <= 4; ++i)
    {
        mylist1.push_back(i);  //1 2 3 4
    }
    for(int i = 1; i <= 3; ++i)
    {
        mylist2.push_back(i * 10);  //10 20 30
    }
    
    cout << "splice之前:" << endl;
    cout << "mylist1: ";
    for(auto e : mylist1)
    {
        cout << e << " ";
    }
    cout << endl;
    cout << "mylist2: ";
    for (auto e : mylist2)
    {
        cout << e << " ";
    }
    cout << endl;

    it = mylist1.begin();
    ++it;  //it指向mylist1中2的位置
    mylist1.splice(it, mylist2);  //把mylist2转移到it指向位置的前面

    cout << "splice之后:" << endl;
    cout << "mylist1: ";
    for (auto e : mylist1)
    {
        cout << e << " ";
    }
    cout << endl;
    cout << "mylist2: ";
    for (auto e : mylist2)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

示例结果:

在这里插入图片描述

从结果得知,转移意思就是直接把节点取走放到目标对象上!!!

如果指向转移某一个区间的值,则可以如下编写:

#include <iostream>
using namespace std;
#include <list>

void test_list()
{
    list<int> mylist1, mylist2;
    list<int>::iterator it;

    for(int i = 1; i <= 4; ++i)
    {
        mylist1.push_back(i);  //1 2 3 4
    }
    for(int i = 1; i <= 3; ++i)
    {
        mylist2.push_back(i * 10);  //10 20 30
    }
    
    cout << "splice之前:" << endl;
    cout << "mylist1: ";
    for(auto e : mylist1)
    {
        cout << e << " ";
    }
    cout << endl;
    cout << "mylist2: ";
    for (auto e : mylist2)
    {
        cout << e << " ";
    }
    cout << endl;

    it = mylist1.begin();
    ++it;  //it指向mylist1中2的位置
    mylist1.splice(it, mylist2, ++mylist2.begin(), mylist2.end());      //此处修改
	//从begin后一个位置开始(第二个位置)后的节点转移到目标链表中  

    cout << "splice之后:" << endl;
    cout << "mylist1: ";
    for (auto e : mylist1)
    {
        cout << e << " ";
    }
    cout << endl;
    cout << "mylist2: ";
    for (auto e : mylist2)
    {
        cout << e << " ";
    }
    cout << endl;
}

int main()
{
    test_list();
    return 0;
}

演示结果:

在这里插入图片描述

3.list模拟实现

list定义新节点的函数为:list_node<typedef>

迭代器的定义:__list_iterator<typedef>

lish.h 内容:

#include <iostream>
using namespace std;
#include <list>
#include <vector>
namespace pzh
{
	template <class T>
	struct list_node // 定义
	{
		T _data;
		list_node<T> *_next;
		list_node<T> *_prev;

		list_node(const T &x = T()) // T不一定是int,需要给个匿名对象   // 构造函数
			: _data(x), _next(nullptr), _prev(nullptr)
		{
		}
	};

	template <class T, class Ref, class Ptr> // 充当 Ref=T&  Ptr=T*
	struct __list_iterator					 // 迭代器
	{
		typedef list_node<T> Node;
		typedef __list_iterator<T, Ref, Ptr> self;
		Node *_node;

		__list_iterator(Node *node) // 构造
			: _node(node)
		{
		}

		self &operator++()
		{
			_node = _node->_next;
			return *this;
		}

		self &operator--()
		{
			_node = _node->_prev;
			return *this;
		}

		self operator++(int)
		{
			self tmp(*this);
			_node = _node->_next;
			return tmp;
		}

		self operator--(int)
		{
			self tmp(*this);
			_node = _node->_prev;
			return tmp;
		}

		Ref operator*()
		{
			return _node->_data;
		}

		Ptr operator->()
		{
			return &_node->_data;
		}

		bool operator!=(const self &s)
		{
			return _node != s._node;
		}

		bool operator==(const self &s)
		{
			return _node == s._node;
		}
	};

	// template <class T>
	// struct __list_const_iterator // const迭代器
	// {
	// 	typedef list_node<T> Node;
	// 	typedef __list_const_iterator<T> self;
	// 	Node *_node;

	// 	__list_const_iterator(Node *node) // 构造
	// 		: _node(node)
	// 	{
	// 	}

	// 	self &operator++()
	// 	{
	// 		_node = _node->_next;
	// 		return *this;
	// 	}

	// 	self &operator--()
	// 	{
	// 		_node = _node->_prev;
	// 		return *this;
	// 	}

	// 	self operator++(int)
	// 	{
	// 		self tmp(*this);
	// 		_node = _node->_next;
	// 		return tmp;
	// 	}

	// 	self operator--(int)
	// 	{
	// 		self tmp(*this);
	// 		_node = _node->_prev;
	// 		return tmp;
	// 	}

	// 	const T &operator*()
	// 	{
	// 		return _node->_data;
	// 	}

	// 	const T *operator->()
	// 	{
	// 		return &_node->_data;
	// 	}

	// 	bool operator!=(const self &s)
	// 	{
	// 		return _node != s._node;
	// 	}

	// 	bool operator==(const self &s)
	// 	{
	// 		return _node == s._node;
	// 	}
	// };

	template <class T>
	class list // 类
	{
		typedef list_node<T> Node;

	public:
		typedef __list_iterator<T, T &, T *> iterator;
		typedef __list_iterator<T, const T &, const T *> const_iterator;
		// typedef __list_const_iterator<T> const_iterator;

		iterator begin()
		{
			return _head->_next;
		}
		iterator end()
		{
			return _head;
		}

		const_iterator begin() const
		{
			return _head->_next;
		}
		const_iterator end() const
		{
			return _head;
		}

		void empty_init() // 置空初始化
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;
		}

		list()
		{
			empty_init();
		}

		list(const list<T> &It)
		{
			empty_init();
			for (auto e : It)
			{
				push_back(e);
			}
		}

		void swap(list<T> &It)
		{
			std::swap(_head, It._head);
			std::swap(_size, It._size);
		}

		list<int> &operator=(list<int> &It) // It3(this = It3) = It1 (It1 = It)
		{
			swap(It);
			return *this;
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}

		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}

		void push_back(const T &x)
		{
			insert(end(), x);
		}

		void push_front(const T &x)
		{
			insert(begin(), x);
		}

		void pop_front()
		{
			erase(begin());
		}

		void pop_back()
		{
			erase(--end());
		}

		iterator insert(iterator pos, const T &x) // 插入新节点x
		{
			Node *node = pos._node;
			Node *newnode = new Node(x);
			Node *prev = node->_prev;
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = node;
			node->_prev = newnode;
			++_size;
			return iterator(newnode);
		}

		iterator erase(iterator pos) // 删除节点
		{
			Node *node = pos._node;
			Node *prev = node->_prev;
			Node *next = node->_next;
			delete node;
			prev->_next = next;
			next->_prev = prev;
			--_size;
			return iterator(next);
		}

		size_t size()
		{
			return _size;
		}

	private:
		Node *_head;
		size_t _size;
	};

	void test_list1()
	{
		list<int> It;
		It.push_back(1);
		It.push_back(2);
		It.push_back(3);
		It.push_back(4);
		It.push_back(5);
		list<int>::iterator it = It.begin();
		while (it != It.end())
		{
			cout << *it << endl;
			++it;
		}
		cout << endl;
		for (auto e : It)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test_list2()
	{
		list<int> It1;
		It1.push_back(1);
		It1.push_back(2);
		It1.push_back(3);
		It1.push_back(4);
		It1.push_back(5);

		cout << "It1: ";
		for (auto e : It1)
		{
			cout << e << " ";
		}
		cout << endl;

		list<int> It2;
		cout << "拷贝前It2: ";
		for (auto e : It2)
		{
			cout << e << " ";
		}
		cout << endl;
		It2 = It1; // 拷贝构造
		cout << "拷贝后It2: ";
		for (auto e : It2)
		{
			cout << e << " ";
		}
		cout << endl;
	}

	struct AA
	{
		AA(int a1 = 0, int a2 = 0)
			: _a1(a1), _a2(a2)
		{
		}
		int _a1;
		int _a2;
	};
	void test_list3()
	{
		list<AA> It;
		It.push_back(AA(1, 1));
		It.push_back(AA(2, 2));
		It.push_back(AA(3, 3));
		It.push_back(AA(4, 4));
		list<AA>::iterator it = It.begin();
		while (it != It.end())
		{
			// cout << (*it)._a1 << " " << (*it)._a2 << endl;
			cout << it->_a1 << " " << it->_a2 << endl; // 迭代器不支持箭头,需要重载
			++it;
		}
	}

	  const  

	// 只能输出int
	void print_list(const list<int> &It)
	{
		list<int>::const_iterator it = It.begin();
		while (it != It.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;

		// for(auto e : It)
		// {
		// 	cout << e << " ";
		// }
		// cout << endl;
	}

	// 可以输出list的任意类型
	template <typename T> // T没有实例化  	//先实例化
	// template <class T> // 直接编译不通过
	void print_list(const list<T> &It)
	{
		// list<T>::const_iterator it = It.begin();  //直接编译不通过

		/* list<T>未实例化的类模板,比那一其不能去它里面去找
		   编译器就无法list<T>::const_iterator是内嵌类型,还是静态成员变量
		   前面加一个typename就是告诉编译器,这里是一个类型,等list<T>实例化再去类里面去取*/	   
		typename list<T>::const_iterator it = It.begin(); // 不加typename,list<T>没有实例化
		while (it != It.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;
	}

	// 可以输出任意容器的类型
	template <typename Container>
	void print_Container(const Container &con)
	{
		typename Container::const_iterator it = con.begin();
		while (it != con.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;
	}

	void test_list4()
	{
		list<int> It;
		It.push_back(1);
		It.push_back(2);
		It.push_back(3);
		It.push_back(4);
		It.push_back(5);
		//print_list(It);
		print_Container(It);

		list<string> It1;
		It1.push_back("s");
		It1.push_back("o");
		It1.push_back("l");
		It1.push_back("i");
		It1.push_back("t");
		It1.push_back("y");
		//print_list(It1);
		print_Container(It1);

		vector<string> It2;
		It2.push_back("p");
		It2.push_back("z");
		It2.push_back("h");
		print_Container(It2);
	}
}

main.cpp 内容 :

#include "list.h"
int main()
{
	pzh::test_list1();
	pzh::test_list2();
	pzh::test_list3();
	pzh::test_list4();
	return 0;
}

4. list与vector的对比

vector与list都是STL中非常重要的序列式容器,由于两个容器的底层结构不同,导致其特性以及应用场景不同,其主要不同如下:

vector list
底 层 结 构 动态顺序表,一段连续空间 带头结点的双向循环链表
随 机 访 问 支持随机访问,访问某个元素效率O(1) 不支持随机访问,访问某个元素效率O(n)
插 入 和 删 除 任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低 任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)
空 间 利 用 率 底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高 底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低
迭 代 器 原生态指针 对原生态指针(节点指针)进行封装
迭 代 器 失 效 在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值否则会失效 插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使 用 场 景 需要高效存储,支持随机访问,不关心插入删除效率 大量插入和删除操作,不关心随机访问

网站公告

今日签到

点亮在社区的每一天
去签到