C++初级----list(STL)

1、 list介绍

1.1、 list介绍

1.list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。 
    1. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向 其前一个元素和后一个元素。 
    2. list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高 效。
    3. 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率 更好。
    4. 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list 的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间 开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这 可能是一个重要的因素)

1.2 、list的使用

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

1.3、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.4 list iterator的使用

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

【注意】

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

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

1.5 list element access

1.6 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中的有效元素

1.7 list的迭代器失效

        迭代器失效即迭代器所指向的节点的无效,即该节 点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代 器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。

2、list的模拟实现

2.1 list的反向迭代器

        通过前面例子知道,反向迭代器的++就是正向迭代器的--,反向迭代器的--就是正向迭代器的++,因此反向迭 代器的实现可以借助正向迭代器,即:反向迭代器内部可以包含一个正向迭代器,对正向迭代器的接口进行 包装即可。

template<class Iterator>
class ReverseListIterator
{
public:
    typedef typename Iterator::Ref Ref;
    typedef typename Iterator::Ptr Ptr;
    typedef ReverseListIterator<Iterator> Self;

public:
    // 构造
    ReverseListIterator(Iterator it): _it(it) {}

    // 具有指针类似行为
    Ref operator*()
    {
        Iterator temp(_it);
        --temp;
        return *temp;
    }

    Ptr operator->()
    {
        return &(operator*());
    }

    // 迭代器支持移动
    Self& operator++()
    {
        --_it;
        return *this;
    }

    Self operator++(int)
    {
        Self temp(*this);
        --_it;
        return temp;
    }

    Self& operator--()
    {
        ++_it;
        return *this;
    }

    Self operator--(int)
    {
        Self temp(*this);
        ++_it;
        return temp;
    }

    // 迭代器支持比较
    bool operator!=(const Self& l) const
    {
        return _it != l._it;
    }

    bool operator==(const Self& l) const
    {
        return _it != l._it;
    }

    Iterator _it;
};

2.2、list的模拟实现

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
namespace kzy {
	template<class T>
	struct list_node {
		list_node<T>* _prev;
		list_node<T>* _next;
		T _data;

		list_node(const T& val = T())
			:_prev(nullptr)
			,_next(nullptr)
			,_data(val)
		{}
	};

	template<class T, class Ref,class Ptr>
	struct _list_iterator
	{
		typedef list_node<T> Node;
		typedef _list_iterator<T, Ref, Ptr> self;
		
		Node* _node;

		_list_iterator(Node* node)
			:_node(node)
		{}

		Ref operator*() 
		{
			return _node->_data;
		}
		Ptr operator->()
		{
			//return &(operator*());
			return &_node->_data;
		}
		self& operator++() 
		{
			_node=_node->_next;
			return *this;
		}
		self operator++(int)
		{
			self* tmp(*this);
			_node = _node->next;
			return tmp;
		}
		self& operator--() 
		{
			_node = _node->_prev;
			return *this;
		}
		self operator--(int)
		{
			self* tmp(*this);
			_node = _node->_prev;
			return tmp;
		}
		bool operator!=(const self& it)
		{
			return _node != it._node;
		}
		bool operator==(const self& it)
		{
			return _node == it._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;
		const_iterator begin() const
		{
			return const_iterator(_head->_next);
		}
		const_iterator end() const
		{
			return const_iterator(_head);
		}
		iterator begin()
		{
			return iterator(_head->_next);
		}
		iterator end() 
		{
			return iterator(_head);
		}

	

		list() 
		{
			_head = new Node();
			_head->_next = _head;
			_head->_prev = _head;
		}
		void empty_init() 
		{
			_head = new Node();
			_head->_next = _head;
			_head->_prev = _head;
		}
		template <class InputIterator>
		list(InputIterator first, InputIterator last)
		{
			empty_init();

			while (first != last)
			{
				push_back(*first);
				++first;
			}
		}
		void swap(list<T>& lt)
		{
			std::swap(_head, lt._head);
		}

		list(const list<T>& it)
		{
			empty_init();
			list<T> tmp = list(it.begin(), it.end());
			swap(tmp);

		}
		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}
		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}
		void clear()
		{
			iterator it = begin();
			while (it != end()) {
				it=erase(it);
			}
		}
		iterator erase(iterator pos) 
		{
			assert(pos != end());
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* next = cur->_next;
			prev->_next = next;
			next->_prev = prev;
			delete cur;
			return iterator(next);
		}
		void push_back(const T& x) 
		{
			insert(end(),x);
		}
		void push_front(const T& x)
		{
			insert(begin(), x);
		}
		void pop_back() 
		{
			erase(--end());
		}
		void pop_front() 
		{
			erase(begin());
		}
		iterator insert(iterator pos, const T& x)
		{
			Node* newnode = new Node(x);
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			
			prev->_next = newnode;
			newnode->_prev = prev;
			newnode->_next = cur;
			cur->_prev = newnode;

			return iterator(newnode);
		}
	private:
		Node* _head;
	};

	void print_list(const list<int>& lt)
	{
		list<int>::const_iterator it = lt.begin();
		while (it != lt.end())
		{
			//*it = 10; // 不允许修改
			cout << *it << " ";
			++it;
		}
		cout << endl;
	}
	void test_list1()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);

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

		print_list(lt);
	}

	struct AA
	{
		AA(int a1 = 0, int a2 = 0)
			:_a1(a1)
			, _a2(a2)
		{}

		int _a1;
		int _a2;
	};

	void test_list2()
	{
		list<AA> lt;
		lt.push_back(AA(1, 1));
		lt.push_back(AA(2, 2));
		lt.push_back(AA(3, 3));
		lt.push_back(AA(4, 4));

		// 迭代器模拟的是指针行为
		// int* it  *it
		// AA*  it  *it  it->
		list<AA>::iterator it = lt.begin();
		while (it != lt.end())
		{
			//cout << (*it)._a1 << "-"<< (*it)._a2 <<" ";
			cout << it->_a1 << "-" << it->_a2 << " ";
			++it;
		}
		cout << endl;
	}


	void test_list3()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);

		lt.push_front(1);
		lt.push_front(2);
		lt.push_front(3);
		lt.push_front(4);
		for (auto e : lt)
		{
			cout << e << " ";
		}
		cout << endl;

		lt.pop_front();
		lt.pop_front();

		lt.pop_back();
		lt.pop_back();

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

	void test_list4()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);
		lt.push_back(5);
		lt.push_back(6);

		// 要求在偶数的前面插入这个偶数*10
		auto it1 = lt.begin();
		while (it1 != lt.end())
		{
			if (*it1 % 2 == 0)
			{
				lt.insert(it1, *it1 * 10);
			}

			++it1;
		}

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

	void test_list5()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);
		lt.push_back(5);
		lt.push_back(6);

		// 删除所有的偶数
		/*auto it1 = lt.begin();
		while (it1 != lt.end())
		{
			if (*it1 % 2 == 0)
			{
				lt.erase(it1);
			}

			++it1;
		}*/

		auto it1 = lt.begin();
		while (it1 != lt.end())
		{
			if (*it1 % 2 == 0)
			{
				it1 = lt.erase(it1);
			}
			else
			{
				++it1;
			}
		}

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

		lt.clear();

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

		lt.push_back(10);
		lt.push_back(20);
		lt.push_back(30);

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

	void test_list6()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);
		lt.push_back(5);
		lt.push_back(6);

		list<int> lt1(lt);

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

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

		list<int> lt2;
		lt2.push_back(10);
		lt2.push_back(20);
		lt1 = lt2;
		for (auto e : lt2)
		{
			cout << e << " ";
		}
		cout << endl;

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

3、list和vector对比

vector

list

底层结构

动态顺序表,一段连续空间

带头结点的双向循环链表

随机访问

支持随机访问,访问某个元素效率O(1)

不支持随机访问,访问某个元素效率O(N)

插入和删除

任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低

任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)

空间利用率

底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高

底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低

迭代器

原生态指针

对原生态指针(节点指针)进行封装

迭代器失效

在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值否则会失效

插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响

使用场景

需要高效存储,支持随机访问,不关心插入删除效率

大量插入和删除操作,不关心随机访

相关推荐

  1. C语言之初级指针

    2024-04-21 07:12:02       37 阅读
  2. C++初级---模板初阶

    2024-04-21 07:12:02       19 阅读
  3. <span style='color:red;'>C</span>++<span style='color:red;'>初学</span>

    C++初学

    2024-04-21 07:12:02      20 阅读
  4. <span style='color:red;'>c</span>++<span style='color:red;'>初步</span>

    c++初步

    2024-04-21 07:12:02      17 阅读
  5. <span style='color:red;'>初始</span><span style='color:red;'>C</span>++

    初始C++

    2024-04-21 07:12:02      10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-21 07:12:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-21 07:12:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-21 07:12:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-21 07:12:02       20 阅读

热门阅读

  1. 农业大数据概论-按章节复习

    2024-04-21 07:12:02       15 阅读
  2. npm常用命令详解(一)

    2024-04-21 07:12:02       11 阅读
  3. UGUI父对象自适应子元素布局解决方案

    2024-04-21 07:12:02       14 阅读
  4. WPF Dispatcher使用invoke造成死锁

    2024-04-21 07:12:02       16 阅读
  5. MVC、MVP、MVVM

    2024-04-21 07:12:02       14 阅读
  6. leetcode821-Shortest Distance to a Character

    2024-04-21 07:12:02       13 阅读