1 list的介绍和使用

1.1 list的介绍

list介绍文档

1.2 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 的使用

        我们可以将iterator理解为一个指针里面存着一个结点,但是他和普通指针不同之处在于,它除了存着结点还存着方法

函数声明接口说明
begin+ end返回第一个元素的迭代器;返回最后一个元素下一个位置的迭代器
rbegin + rend返回反向迭代器 rbegin(对应正向 end 位置);rend 反向迭代器(对应正向 begin 位置),用于逆序遍历容器

注意:
        1 begin和end都是正向迭代器,对迭代器进行++操作,迭代器向后操作
        2 rbegin和rend都是反向迭代器,对迭代器进行++操作,迭代器向后操作

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的文档说明,这里就不做过多的说明只挑重要的探讨。

2 再探iterator迭代器

2.1 迭代器分类

2.1.1 随机迭代器       

        iterator支持 ++/--/+/-
例如:vector/string/......

2.1.2 双向迭代器

        iterator支持 ++/--
例如:list/map/set/......


2.1.3 单向迭代器

        iterator支持 +/-
例如:forward_list/undordered_map/......

2.2 迭代器和指针的异同

2.2.1指针
  • 直接存储内存地址,*p 就是解引用访问内存;
  • 只适用于连续内存:数组、堆上连续分配内存;
  • 自增 p++ 等价于地址偏移 +sizeof(T)
2.2.2迭代器

不同容器迭代器实现完全不同:

  • vector/deque:本质就是封装后的指针(随机访问迭代器);
  • list/map/set:完全不是指针,是指向链表节点、红黑树节点的对象,内部存节点指针;
  • string:同样封装指针;
  • 甚至可以有无内存地址的迭代器(如 istream_iterator)。

迭代器有着指针没有的优势是,可以通过类的方法实现更多操作


2.3 list 迭代器失效

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

错误写法:
 

void TestListIterator1()
{ 
    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 TestListIterator1()
{ 
    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);
    }
}

3 list的模拟实现

3.1 list 的实现

#pragma once
#include <iostream>
using namespace std;

namespace yjs
{
	template<class T>
	struct ListNode
	{
        ListNode(const T& value =T())
			:_data(value)
			,_next(nullptr)
			,_prev(nullptr)
		{

		}
		T _data;
        ListNode<T>* _next;
        ListNode<T>* _prev;
	};

    //List的迭代器类
    template<class T, class Ref, class Ptr>
    struct ListIterator
    {
        typedef ListNode<T>* PNode;
        typedef ListIterator<T, Ref, Ptr> Self;
        ListIterator(PNode pNode = nullptr)
        {
            _pNode = pNode;
        }
        ListIterator(const Self& l)
        {
            _pNode = l._pNode;
        }
        T& operator*()
        {
            return _pNode->_data;
        }
        T* operator->()
        {
            return &(_pNode->_data);
        }
        Self& operator++()
        {
            _pNode = _pNode->_next;
            return *this;
        }
        Self operator++(int)
        {
            _pNode = _pNode->_next;
            return *this;
        }
        Self& operator--()
        {
            _pNode = _pNode->_prev;
            return *this;
        }
        Self operator--(int)
        {
            _pNode = _pNode->_prev;
            return *this;
        }
        bool operator!=(const Self& l)
        {
            return _pNode != l._pNode;
        }
        bool operator==(const Self& l)
        {
            return _pNode == l._pNode;
        }
        PNode _pNode;
    };

    //list类
    template<class T>
    class list
    {
        typedef ListNode<T> Node;
        typedef Node* PNode;
    public:
        typedef ListIterator<T, T&, T*> iterator;
        typedef ListIterator<T, const T&, const T*> const_iterator;
    public:
        ///////////////////////////////////////////////////////////////
        // List的构造
        list()
        {
            _pHead = new Node[1];
            _pHead->_next = _pHead;
            _pHead->_prev = _pHead;

        }
        list(int n, const T& value = T())
        {
            for (int i = 0; i < n; i++)
            {
                Node* newnode = new Node(value);
                Node* tail = _pHead->_prev;
                tail->_next = newnode;
                newnode->_prev = tail;
                newnode->_next = _pHead;
                _pHead->_prev = newnode;
            }
        }
        template <class Iterator>
        list(Iterator first, Iterator last)
        {
            _pHead = new Node(T());
            Iterator cur = first;
            while (cur!=last)
            {
                Node* newnode = new Node(*cur);
                Node* tail = _pHead->_prev;
                tail->_next = newnode;
                newnode->_prev = tail;
                newnode->_next = _pHead;
                _pHead->_prev = newnode;
                cur++;
            }
            Node* newnode = new Node(*last);
            Node* tail = _pHead->_prev;
            tail->_next = newnode;
            newnode->_prev = tail;
            newnode->_next = _pHead;
            _pHead->_prev = newnode;
        }

        list(const list<T>& l)
        {
            _pHead = new Node(T());
            Node* cur = l._pHead->next;
            while (cur != l.pHead)
            {
                Node* newnode = new Node(cur->_data);
                Node* tail = _pHead->_prev;
                tail->_next = newnode;
                newnode->_prev = tail;
                newnode->_next = _pHead;
                _pHead->_prev = newnode;
                cur = cur->_next;
            }
        }

        list<T>& operator=(const list<T> l)
        {
            Node* cur = _pHead->_next;
            while (cur != _pHead)
            {
                Node* next = cur->_next;
                delete cur;
                cur = next;
            }
            delete _pHead;

            _pHead = new Node(T());
            cur = l._pHead->next;
            while (cur != l.pHead)
            {
                Node* newnode = new Node(cur->_data);
                Node* tail = _pHead->_prev;
                tail->_next = newnode;
                newnode->_prev = tail;
                newnode->_next = _pHead;
                _pHead->_prev = newnode;
                cur = cur->_next;
            }
        }

        ~list()
        {
            Node* cur = _pHead->_next;
            while (cur!=_pHead)
            {
                Node* next = cur->_next;
                delete cur;
                cur = next;
            }
            delete cur;
        }


        ///////////////////////////////////////////////////////////////
        // List Iterator
        iterator begin()
        {
            return { _pHead->_next};
        }
        iterator end()
        {
            return { _pHead };
        }
        const_iterator cbegin() 
        {
            return { _pHead->_next };
        }
        const_iterator cend() 
        {
            return { _pHead };
        }


        ///////////////////////////////////////////////////////////////
        // List Capacity
        size_t size()const
        {
            int i = 0;
            Node* cur = _pHead->_next;
            while (cur != _pHead)
            {
                i++;
                cur = cur->next;
            }
        }
        bool empty()const
        {
            return _pHead == _pHead->_next;
        }


        ////////////////////////////////////////////////////////////
        // List Access
        T& front()
        {
            return _pHead->_next->_date;
        }
        const T& front()const
        {
            return _pHead->_next->_date;
        }
        T& back()
        {
            return _pHead->_prev->_date;
        }
        const T& back()const
        {
            return _pHead->_prev->_date;
        }


        ////////////////////////////////////////////////////////////
        // List Modify
        void push_back(const T& val) 
        { 
            insert(end(), val);
        }
        void pop_back()
        { 
            erase(--end());
        }
        void push_front(const T& val) 
        {
            insert(begin(), val);
        }
        void pop_front() 
        {
            erase(begin()); 
        }
        // 在pos位置前插入值为val的节点
        iterator insert(iterator pos, const T& val)
        {
            Node* newnode = new Node(val);
            Node* prev = pos._pNode->_prev;
            prev->_next = newnode;
            newnode->_next = pos._pNode;
            newnode->_prev = prev;
            pos._pNode->_prev = newnode;
            return { newnode };
        }
        // 删除pos位置的节点,返回该节点的下一个位置
        iterator erase(iterator pos)
        {
            Node* prev = pos._pNode->_prev;
            Node* next = pos._pNode->_next;
            prev->_next = next;
            next->_prev= prev;
            delete pos._pNode;
            return { next };
        }
        void clear()
        {
            Node* cur = _pHead->_next;
            while (cur != _pHead)
            {
                Node* next = cur->_next;
                delete cur;
                cur = next;
            }
            _pHead->_next = _pHead;
            _pHead->_prev = _pHead;

        }
        void swap(list<T>& l)
        {
            PNode temp = l._pHead;
            l._pHead = _pHead;
            _pHead = temp;
        }
    private:

        PNode _pHead;
    };

}

拓展: 3.2 list 反向迭代器的实现
 

#pragma once

namespace yjs
{
	template<class Iterator, class Ref, class Ptr >
	struct ReverseIterator
	{
		typedef ReverseIterator<Iterator, Ref, Ptr> Self;
		ReverseIterator(Iterator it)
			:_it(it)
		{

		}
		Ref operator*()
		{
			Iterator temp = _it;
			--temp;
			return *temp;
		}
		Ptr operator->()
		{
			return &(operator*());
		}

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

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

		bool operator!=(Self it)
		{
			return _it != it._it;
		}

		bool operator==(Self it)
		{
			return _it == it._it;
		}

		Iterator _it;
	};
}

反向迭代器的原理就是让原来正向迭代器的--变为反向迭代器的++,实现用了适配器的思想,这个思想会在后面学习stack和queue的时候详细介绍现在只单纯了解

4 list和vector的对比

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

对比维度vectorlist
底层结构动态顺序表,占用一段连续内存空间带头结点的双向循环链表
随机访问支持随机访问,下标访问元素时间复杂度 O (1)不支持随机访问,遍历查找元素 O (N)
插入和删除任意位置增删效率低,需要挪动大量元素,复杂度 O (N)。扩容还需开辟新空间、拷贝释放旧空间,开销更大任意位置增删效率高,仅修改指针指向,无需移动元素,复杂度 O (1)
空间利用率连续内存,不易产生内存碎片,空间利用率高,CPU 缓存命中率高节点零散动态分配,易造成内存碎片,空间利用率低,缓存命中率差
迭代器本质原生指针对链表节点指针进行封装的迭代器,加入了方法
迭代器失效规则插入可能触发扩容,导致全部迭代器失效删除仅当前迭代器失效插入操作迭代器均不失效删除仅被删除元素对应的迭代器失效,其余不受影响
适用场景需要随机访问、看重缓存效率、较少中间插入删除,追求高效连续存储频繁在任意位置插入 / 删除元素,不需要随机访问功能

更多推荐