【C++】一篇文章带你深入了解list

在这里插入图片描述

目录

  • 一、list的介绍
  • 二、 标准库中的list类
    • 2.1 list的常见接口说明
      • 2.1.1 list对象的常见构造
        • 2.1.1.1 [无参构造函数](https://legacy.cplusplus.com/reference/list/list/list/)
        • 2.1.1.2 [有参构造函数(构造并初始化n个val)](https://legacy.cplusplus.com/reference/list/list/list/)
        • 2.1.1.3 [有参构造函数(使用迭代器进行初始化构造)](https://legacy.cplusplus.com/reference/list/list/list/)
        • 2.1.1.4 [拷贝构造函数](https://legacy.cplusplus.com/reference/list/list/list/)
      • 2.1.2 list iterator的使用
        • 2.1.2.1 [begin()](https://legacy.cplusplus.com/reference/list/list/begin/) + [end()](https://legacy.cplusplus.com/reference/list/list/end/)
        • 2.1.2.2 [rbegin()](https://legacy.cplusplus.com/reference/list/list/rbegin/) + [rend()](https://legacy.cplusplus.com/reference/list/list/rend/)
      • 2.1.3 list对象的容量操作
        • 2.1.3.1 [empty()函数](https://legacy.cplusplus.com/reference/list/list/empty/)
        • 2.1.3.2 [size()函数](https://legacy.cplusplus.com/reference/list/list/size/)
      • 2.1.4 list对象的增删查改及访问
        • 2.1.4.1 [push_front()函数](https://legacy.cplusplus.com/reference/list/list/push_front/)
        • 2.1.4.2 [pop_front()函数](https://legacy.cplusplus.com/reference/list/list/pop_front/)
        • 2.1.4.3 [push_back()函数](https://legacy.cplusplus.com/reference/list/list/push_back/)
        • 2.1.4.4 [pop_back()函数](https://legacy.cplusplus.com/reference/list/list/pop_back/)
        • 2.1.4.5 [insert()函数](https://legacy.cplusplus.com/reference/list/list/insert/)
        • 2.1.4.6 [erase()函数](https://legacy.cplusplus.com/reference/list/list/erase/)
        • 2.1.4.7 [swap()函数](https://legacy.cplusplus.com/reference/list/list/swap/)
        • 2.1.4.8 [clear()函数](https://legacy.cplusplus.com/reference/list/list/clear/)
        • 2.1.4.9 [front()函数](https://legacy.cplusplus.com/reference/list/list/front/) + [back()函数](https://legacy.cplusplus.com/reference/list/list/back/)
      • 2.1.5 list的迭代器失效
  • 三、list的模拟实现
    • 3.1 list 节点类的实现
    • 3.2 list 中默认成员函数的实现
    • 3.3 list 中 size、empty 和 swap 函数的实现
    • 3.4 list 中 迭代器类 的实现
    • 3.5 list 中 迭代器 、 范围构造函数 和 clear 函数 的实现
    • 3.6 list 中 insert 和 erase 的实现
    • 3.7 list 中 push_back、pop_back、push_front 和 pop_front 函数的实现
    • 3.8 list 中 反向迭代器类 和 反向迭代器 的实现
    • 3.9 list 实现汇总及函数测试
  • 四、 list 与 vector 的对比
  • 结尾

一、list的介绍

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

二、 标准库中的list类

2.1 list的常见接口说明

2.1.1 list对象的常见构造

2.1.1.1 无参构造函数
list();
int main()
{
	list<int> l;

	return 0;
}

在这里插入图片描述


2.1.1.2 有参构造函数(构造并初始化n个val)
list (size_type n, const value_type& val = value_type());
int main()
{
	list<int> l(5, 4);

	return 0;
}

在这里插入图片描述


2.1.1.3 有参构造函数(使用迭代器进行初始化构造)
template <class InputIterator>
 	 list (InputIterator first, InputIterator last);
int main()
{
	string s("Love");
	list<int> l(s.begin(), s.end());

	return 0;
}

在这里插入图片描述


2.1.1.4 拷贝构造函数
list (const list& x);
int main()
{
	list<int> l1(5,6);
	list<int> l2(l1);

	return 0;
}

在这里插入图片描述


2.1.2 list iterator的使用

2.1.2.1 begin() + end()
	  iterator begin();
const_iterator begin() const;
获取第一个数据位置的iterator/const_iterator

 	  iterator end();
const_iterator end() const;
获取最后一个数据的下一个位置的iterator/const_iterator
int main()
{
	list<int> l;
	for (int i = 0; i < 10; i++)
	{
		l.push_back(i);
	}

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

	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.2.2 rbegin() + rend()
	  reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
获取最后一个数据位置的reverse_iterator/const_reverse_iterator 

	  reverse_iterator rend();
const_reverse_iterator rend() const;
获取第一个数据前一个位置的reverse_iterator/const_reverse_iterator 
int main()
{
	list<int> l;
	for (int i = 0; i < 10; i++)
	{
		l.push_back(i);
	}

	list<int>::reverse_iterator it = l.rbegin();
	while (it != l.rend())
	{
		cout << *it << ' ';
		++it;
	}

	cout << endl;

	return 0;
}

在这里插入图片描述

注意

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

2.1.3 list对象的容量操作

2.1.3.1 empty()函数
bool empty() const;         判断是否为空
int main()
{
	list<int> l;
	cout << l.empty() << endl;

	l.push_back(1);
	cout << l.empty() << endl;

	return 0;
}

在这里插入图片描述

2.1.3.2 size()函数
size_type size() const;      获取数据个数
int main()
{
	list<int> l;
	cout << l.size() << endl;

	for (int i = 0; i < 10; i++)
	{
		l.push_back(i);
	}

	cout << l.size() << endl;

	return 0;
}

2.1.4 list对象的增删查改及访问

2.1.4.1 push_front()函数
void push_front (const value_type& val);  头插
int main()
{
	list<int> l;
	
	l.push_front(1);
	l.push_front(2);
	l.push_front(3);
	l.push_front(4);

	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.4.2 pop_front()函数
void pop_front();  头删

在这里插入图片描述


2.1.4.3 push_back()函数
void push_back (const value_type& val);   尾插
int main()
{
	list<int> l;

	l.push_back(1);
	l.push_back(2);
	l.push_back(3);
	l.push_back(4);

	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.4.4 pop_back()函数
void pop_back();  尾删
int main()
{
	list<int> l;

	l.push_back(1);
	l.push_back(2);
	l.push_back(3);
	l.push_back(4);

	for (auto e : l)
	{	cout << e << ' ';	}
	cout << endl;

	l.pop_back();

	for (auto e : l)
	{	cout << e << ' ';	}
	cout << endl;
	return 0;
}

在这里插入图片描述


2.1.4.5 insert()函数
iterator insert (iterator position, const value_type& val);
insert()函数能够在position之前插入val,并返回插入数据位置的 iterator 

void insert (iterator position, size_type n, const value_type& val);
insert()函数能够在position之前插入 n 个 val             

template <class InputIterator>
		void insert (iterator position, InputIterator first, InputIterator last);
insert()函数能够在position之前插入一段迭代器区间的数据       		
int main()
{
	list<int> l;
	string s("Love");

	l.push_back(1);
	l.push_back(2);

	for (auto e : l)
	{	
		cout << e << ' ';	
	}
	cout << endl;

	// insert()函数能够在position之前插入val,并返回插入数据位置的 iterator 
	cout << *(l.insert(l.begin(), 20)) << endl;

	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	// insert()函数能够在position之前插入 n 个 val        
	l.insert(++l.begin() , 3 ,30);
	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	// insert()函数能够在position之前插入一段迭代器区间的数据       		
	l.insert(++l.begin(), s.begin() , s.end());
	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.4.6 erase()函数
iterator erase (iterator position);
erase()函数能够删除在position位的的数据,并返回删除数据后面数据位置的 iterator

iterator erase (iterator first, iterator last);
erase()函数能够删除在迭代器区间 [first,last) 的的数据,并返回删除数据后面数据位置的 iterator             
int main()
{
	list<int> l;
	
	for (int i = 0; i < 10; i++)
	{
		l.push_back(i);
	}
	cout << endl;

	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	// erase()函数能够删除在position位的的数据
	// 并返回删除数据后面数据位置的 iterator
	cout << *(l.erase(l.begin())) << endl;
	for (auto e : l)
	{
		cout << e << ' ';
	}
	cout << endl;

	// erase()函数能够删除在迭代器区间 [first,last) 的的数据
	// 并返回删除数据后面数据位置的 iterator        
	cout << *(l.erase(++l.begin(),--l.end())) << endl;
	for (auto e : l)
	{
		cout << e << ' ';
	}

	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.4.7 swap()函数
void swap (list& x);
交换两个list的数据空间
int main()
{
	list<int> l1(4, 10);
	list<int> l2(5, 5);

	for (auto e : l1)
	{	cout << e << ' ';	}
	cout << endl;

	for (auto e : l2)
	{	cout << e << ' ';	}
	cout << endl;

	l1.swap(l2);

	for (auto e : l1)
	{	cout << e << ' ';	}
	cout << endl;

	for (auto e : l2)
	{	cout << e << ' ';	}
	cout << endl;

	return 0;
}

在这里插入图片描述


2.1.4.8 clear()函数
void clear();
清除list中的有效数据
int main()
{
	list<int> l(4, 10);
	cout << l.size() << endl;

	l.clear();
	cout << l.size() << endl;

	return 0;
}

在这里插入图片描述


2.1.4.9 front()函数 + back()函数
访问list中的第一个数据
	  reference front();
const_reference front() const;

访问list中的最后一个数据
 	  reference back();
const_reference back() const;
int main()
{
	list<int> l;

	for (int i = 0; i < 10; i++)
	{
		l.push_back(i);
	}

	cout << "front:" << l.front() << endl;
	cout << "back:" << l.back() << endl;

	return 0;
}

在这里插入图片描述


2.1.5 list的迭代器失效

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

int main()
{
	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;
	}

	return 0;
}


// 改正
int main()
{
	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);
	}
}

三、list的模拟实现

3.1 list 节点类的实现

namespace aj
{
    // List的节点类
    template<class T>
    struct ListNode
    {
        ListNode(const T& val = T())
            :_val(val)
        {}

        ListNode<T>* _prev = nullptr;
        ListNode<T>* _next = nullptr;
        T _val;
    };
};

3.2 list 中默认成员函数的实现

namespace aj
{
    //list
    template<class T>
    class list
    {
        typedef ListNode<T> Node;
        typedef Node* PNode;
    
    public:
        // List的构造
        list()
        {
            CreateHead();
        }

        // 构造并用n个val初始化
        list(int n, const T& value = T())
        {
            CreateHead();

            while (n--)
            {
                push_back(value);
            }
        }

        // 链表的拷贝构造
        // list(const list<T>& l)
        list(list<T>& l)
        {
            CreateHead();

            for (auto e : l)
            {
                push_back(e);
            }
        }

        list<T>& operator=(const list<T> l)
        {
            swap(l);

            return *this;
        }
        ~list()
        {
            clear();

            delete _head;
            _head = nullptr;
        }

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

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数

    };
};

3.3 list 中 size、empty 和 swap 函数的实现

namespace aj
{
    template<class T>
    class list
    {
        typedef ListNode<T> Node;
        typedef Node* PNode;
    public:
        size_t size()const
        {
            return size;
        }
        bool empty()const
        {
            return _head->_next == _head && _head->_prev == _head;
        }

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

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数
    };
};

3.4 list 中 迭代器类 的实现

namespace aj
{
    //List的迭代器类
    //template<class T>
    template<class T, class Ref, class Ptr>
    struct ListIterator
    {
        typedef ListNode<T>* PNode;
        typedef ListIterator<T, Ref, Ptr> Self;
        // 成员变量
        PNode _pNode;

    public:
        // 迭代器的构造函数
        ListIterator(PNode pNode = nullptr)
            :_pNode(pNode)
        {}

        Ref operator*()
        {
            return _pNode->_val;
        }

        Ptr operator->()
        {
            return &(_pNode->_val);
        }

        Self& operator++()
        {
            _pNode = _pNode->_next;
            return *this;
        }

        Self operator++(int)
        {
            Self tmp(*this);
            ++* this;
            return tmp;
        }

        Self& operator--()
        {
            _pNode = _pNode->_prev;
            return *this;
        }

        Self operator--(int)
        {
            Self tmp(*this);
            --* this;
            return tmp;
        }

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

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

    };
};

3.5 list 中 迭代器 、 范围构造函数 和 clear 函数 的实现

namespace aj
{
    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;

        template <class Iterator>
        list(Iterator first, Iterator last)
        {
            CreateHead();
            while (first != last)
            {
                push_back(first._pNode->_val);
                ++first;
            }
        }
        
        // List Iterator
        iterator begin()
        {
            // return iterator(_head->_next);
            return _head->_next;
        }

        iterator end()
        {
            // return iterator(_head);
            return _head;
        }

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

        }
        const_iterator end()const
        {
            return _head;
        }

        void clear()
        {
            list<T>::iterator lit = begin();
            while (lit != end())
            {
                lit = erase(lit);
            }
        }

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数
    };
};

3.6 list 中 insert 和 erase 的实现

namespace aj
{
    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;
        
        // 在pos位置前插入值为val的节点,返回插入新节点的位置
        iterator insert(iterator pos, const T& val)
        {
            // 通过迭代器找到所需的节点指针
            Node* cur = pos._pNode;
            Node* prev = cur->_prev;

            // 创建新的节点
            Node* newnode = new Node(val);

            // 节点间相互连接
            newnode->_prev = prev;
            prev->_next = newnode;
            cur->_prev = newnode;
            newnode->_next = cur;

            // 节点数量++
            _size++;

            //return iterator(newnode);
            return newnode;
        }

        // 删除pos位置的节点,返回该节点的下一个位置
        iterator erase(iterator pos)
        {
            assert(_size > 0);
            // 找到所需要的节点指针
            Node* cur = pos._pNode;
            Node* next = cur->_next;
            Node* prev = cur->_prev;

            // 节点相互连接
            next->_prev = prev;
            prev->_next = next;

            // 删除节点
            delete cur;
            cur = nullptr;

            // 减少节点数目
            --_size;
            // 返回删除节点的下一个位置
            // return iterator(next);
            return next;
        }

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数
    };
};

3.7 list 中 push_back、pop_back、push_front 和 pop_front 函数的实现

namespace aj
{
    template<class T>
    class list
    {
    public:
        typedef ListNode<T> Node;
        typedef Node* PNode;
        
        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()); }

    private:
        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数
    };
};


3.8 list 中 反向迭代器类 和 反向迭代器 的实现

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

注意:反向迭代器类可以被所有的容器封装成反向迭代器使用。

下面两种反向迭代器的实现虽然不同,但是功能是相同的。反向迭代器类的实现不同,那么对应封装迭代器的时候也要做出相应的改变。

在这里插入图片描述

reverse_iterator.h 反向迭代器非对称版本
#pragma once

// 不对称版本
namespace aj
{
	// 适配器 -- 复用
	template<class Iterator, class Ref, class Ptr>
	struct Reverse_iterator
	{
		typedef Reverse_iterator<Iterator,Ref,Ptr> Self;

		Reverse_iterator(const Iterator& it)
			:_it(it)
		{}

		Ref operator*()
		{
			return *_it;
		}

		Ptr operator->()
		{
			return _it.operator->();
		}

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

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

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

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

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

		bool operator==(const Self& s)
		{
			return _it == s._it;
		}
		Iterator _it;
	};
}
list.h 反向迭代器非对称版本
#include"reverse_iterator.h"

namespace aj
{
    template<class T>
    class list
    {
    public:
        typedef ListNode<T> Node;
        typedef Node* PNode;
    public:
        // typedef ListIterator<T> iterator;

        typedef ListIterator<T, T&, T*> iterator;
        typedef ListIterator<T, const T&, const T&> const_iterator;
        typedef Reverse_iterator<iterator, T&, T*> reverse_iterator;
        typedef Reverse_iterator<const_iterator, const T&, const T*> const_reverse_iterator;

    public:
 
        // reverse_iterator 不对称版本
        reverse_iterator rbegin()
        {
            // return iterator(_head->_next);
            return --end();    //这里可以使用--end()也可以使用end()-1,但是没有写operator-()
        }                      //这里就使用--end(),这里能使用--end()的原因是
                               //end()返回传值返回的自定义类型的临时对象,具有常性,是常量
                               //但是这里有编译器的特殊处理
                               //使得const对象可以调用非const成员函数

        reverse_iterator rend()
        {
            // return iterator(_head);
            return end();
        }

        const_reverse_iterator rbegin()const
        {
            return --end();

        }
        const_reverse_iterator rend()const
        {
            return end();
        }
    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数

    };
};
reverse_iterator.h 反向迭代器对称版本
#pragma once
// 对称版本
namespace aj
{
	// 适配器 -- 复用
	template<class Iterator, class Ref, class Ptr>
	struct Reverse_iterator
	{
		typedef Reverse_iterator<Iterator,Ref,Ptr> Self;

		Reverse_iterator(const Iterator& it)
			:_it(it)
		{}

		Ref operator*()
		{
			Iterator tmp(_it);
			return *--tmp;
		}

		Ptr operator->()
		{
			return --_it.operator->();
		}

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

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

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

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

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

		bool operator==(const Self& s)
		{
			return _it == s._it;
		}
		Iterator _it;
	};
}
list.h 反向迭代器对称版本
#include"reverse_iterator.h"

namespace aj
{
    template<class T>
    class list
    {
    public:
        typedef ListNode<T> Node;
        typedef Node* PNode;
    public:
        // typedef ListIterator<T> iterator;

        typedef ListIterator<T, T&, T*> iterator;
        typedef ListIterator<T, const T&, const T&> const_iterator;
        typedef Reverse_iterator<iterator, T&, T*> reverse_iterator;
        typedef Reverse_iterator<const_iterator, const T&, const T*> const_reverse_iterator;

    public:
        // reverse_iterator 对称版本
        reverse_iterator rbegin()
        {
            // return iterator(_head->_next);
            return end();
        }

        reverse_iterator rend()
        {
            // return iterator(_head);
            return begin();
        }

        const_reverse_iterator rbegin()const
        {
            return end();

        }
        
        const_reverse_iterator rend()const
        {
            return begin();
        }

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
            _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数

    };
};

3.9 list 实现汇总及函数测试

reverse_iterator.h
#pragma once

// 不对称版本
//namespace aj
//{
//	// 适配器 -- 复用
//	template<class Iterator, class Ref, class Ptr>
//	struct Reverse_iterator
//	{
//		typedef Reverse_iterator<Iterator,Ref,Ptr> Self;
//
//		Reverse_iterator(const Iterator& it)
//			:_it(it)
//		{}
//
//		Ref operator*()
//		{
//			return *_it;
//		}
//
//		Ptr operator->()
//		{
//			return _it.operator->();
//		}
//
//		Self& operator++()
//		{
//			--_it;
//			return *this;
//		}
//
//		Self operator++(int)
//		{
//			Self tmp(*this);
//			--_it;
//			return tmp;
//		}
//
//		Self& operator--()
//		{
//			++_it;
//			return *this;
//		}
//
//		Self operator--(int)
//		{
//			Self tmp(*this);
//			++_it;
//			return tmp;
//		}
//
//		bool operator!=(const Self& s)
//		{
//			return _it != s._it;
//		}
//
//		bool operator==(const Self& s)
//		{
//			return _it == s._it;
//		}
//		Iterator _it;
//	};
//}


// 对称版本
namespace aj
{
	// 适配器 -- 复用
	template<class Iterator, class Ref, class Ptr>
	struct Reverse_iterator
	{
		typedef Reverse_iterator<Iterator,Ref,Ptr> Self;

		Reverse_iterator(const Iterator& it)
			:_it(it)
		{}

		Ref operator*()
		{
			Iterator tmp(_it);
			return *--tmp;
		}

		Ptr operator->()
		{
			return --_it.operator->();
		}

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

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

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

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

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

		bool operator==(const Self& s)
		{
			return _it == s._it;
		}
		Iterator _it;
	};
}
list.h
#pragma once

#include<iostream>
#include<assert.h>
#include <string>
#include <vector>
using namespace std;

#include"reverse_iterator.h"

namespace aj
{
    // List的节点类
    template<class T>
    struct ListNode
    {
        ListNode(const T& val = T())
            :_val(val)
        {}

        ListNode<T>* _prev = nullptr;
        ListNode<T>* _next = nullptr;
        T _val;
    };


    //List的迭代器类
    //template<class T>
    template<class T, class Ref, class Ptr>
    struct ListIterator
    {
        typedef ListNode<T>* PNode;
        typedef ListIterator<T ,Ref , Ptr> Self;
    // 成员变量
        PNode _pNode;

        // typedef ListIterator<T, Ref, Ptr> Self;
    public:
        // 迭代器的构造函数
        ListIterator(PNode pNode = nullptr)
            :_pNode(pNode)
        {}

        Ref operator*()
        {
            return _pNode->_val;
        }

        Ptr operator->()
        {
            return &(_pNode->_val);
        }

        Self& operator++()
        {
            _pNode = _pNode->_next;
            return *this;
        }

        Self operator++(int)
        {
            Self tmp(*this);
            ++* this;
            return tmp;
        }

        Self& operator--()
        {
            _pNode = _pNode->_prev;
            return *this;
        }

        Self operator--(int)
        {
            Self tmp(*this);
            --* this;
            return tmp;
        }

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

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

    };


    //list类
    template<class T>
    class list
    {
    public:
        typedef ListNode<T> Node;
        typedef Node* PNode;
    public:
        // typedef ListIterator<T> iterator;

        typedef ListIterator<T, T&, T*> iterator;
        typedef ListIterator<T, const T&, const T&> const_iterator;
        typedef Reverse_iterator<iterator, T&, T*> reverse_iterator;
        typedef Reverse_iterator<const_iterator,const T&,const T*> const_reverse_iterator;

    public:
        ///
        // List的构造
        list()
        {
            CreateHead();
        }

        list(int n, const T& value = T())
        {
            CreateHead();

            while (n--)
            {
                push_back(value);
            }
        }
        template <class Iterator>
        list(Iterator first, Iterator last)
        {
            CreateHead();
            while (first != last)
            {
                push_back(first._pNode->_val);
                ++first;
            }
        }
        // 链表的拷贝构造
        // list(const list<T>& l)
        list(list<T>& l)
        {
            CreateHead();

            for (auto e : l)
            {
                push_back(e);
            }
        }

        //list<T>& operator=(const list<T> l)
             
        list<T>& operator=(list<T> l)
        {
            swap(l);

            return *this;
        }
        ~list()
        {
            clear();

            delete _head;
            _head = nullptr;
        }


        ///
        // List Iterator
        iterator begin()
        {
            // return iterator(_head->_next);
            return _head->_next;
        }

        iterator end()
        {
            // return iterator(_head);
            return _head;
        }

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

        }
        const_iterator end()const
        {
            return _head;
        }
         reverse_iterator 不对称版本
        //reverse_iterator rbegin()
        //{
        //    // return iterator(_head->_next);
        //    return --end();    //这里可以使用--end()也可以使用end()-1,但是没有写operator-()
        //}                      //这里就使用--end(),这里能使用--end()的原因是
        //                       //end()返回传值返回的自定义类型的临时对象,具有常性,是常量
        //                       //但是这里有编译器的特殊处理
        //                       //使得const对象可以调用非const成员函数
                                 
        //reverse_iterator rend()
        //{
        //    // return iterator(_head);
        //    return end();
        //}

        //const_reverse_iterator rbegin()const
        //{
        //    return --end();

        //}
        //const_reverse_iterator rend()const
        //{
        //    return end();
        //}

        // reverse_iterator 对称版本
        reverse_iterator rbegin()
        {
            // return iterator(_head->_next);
            return end();
        }

        reverse_iterator rend()
        {
            // return iterator(_head);
            return begin();
        }

        const_reverse_iterator rbegin()const
        {
            return end();

        }
        const_reverse_iterator rend()const
        {
            return begin();
        }

        ///
        // List Capacity
        size_t size()const
        {
            return size;
        }
        bool empty()const
        {
            return _head->_next == _head && _head->_prev == _head;
         }

        
        // List Access
        T& front()
        {
            assert(_head->_next != _head);
            return _head->_next->_val;
        }

        const T& front()const
        {
            assert(_head->_next != _head);
            return _head->_next->_val;
        }
        T& back()
        {
            assert(_head->_prev != _head);
            return _head->_prev->_val;
        }
        const T& back()const
        {
            assert(_head->_prev != _head);
            return _head->_prev->_val;
        }


        
        // 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* cur = pos._pNode;
            Node* prev = cur->_prev;

            // 创建新的节点
            Node* newnode = new Node(val);

            // 节点间相互连接
            newnode->_prev = prev;
            prev->_next = newnode;
            cur->_prev = newnode;
            newnode->_next = cur;

            // 节点数量++
            _size++;

            //return iterator(newnode);
            return newnode;
        }

        // 删除pos位置的节点,返回该节点的下一个位置
        iterator erase(iterator pos)
        {
            assert(_size > 0);
            // 找到所需要的节点指针
            Node* cur = pos._pNode;
            Node* next = cur->_next;
            Node* prev = cur->_prev;

            // 节点相互连接
            next->_prev = prev;
            prev->_next = next;

            // 删除节点
            delete cur;
            cur = nullptr;

            // 减少节点数目
            --_size;
            // 返回删除节点的下一个位置
            // return iterator(next);
            return next;
        }

        void clear()
        {
            list<T>::iterator lit = begin();
            while (lit != end())
            {
                lit = erase(lit);
            }
        }

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

    private:
        void CreateHead()
        {
            _head = new Node();
            _head->_next = _head;
             _head->_prev = _head;

            _size = 0;
        }

        PNode _head;    // 头结点
        int _size;      // 记录链表中节点的个数

    };


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

        int _a1;
        int _a2;
    };

    //template<class T>
    //void print_list(const list<T>& l)
    //{
    //    // list<T>未实例化的类模板,编译器不能去他里面去找
    //    // 那么编译器就无法确定这里的
    //    // const_iterator是静态变量还是内嵌类型
    //    // 加上typename就相当于告诉编译器这里是内嵌类型
    //    // 等list<T>初始化后再到类中去取
    //    typename list<T>::const_iterator it = l.begin();
    //    while (it != l.end())
    //    {
    //        cout << *it << ' ';
    //        ++it;
    //    }
    //    cout << endl;
    //}


    template<class Container>
    void print_container(const Container& l)
    {
        typename Container::const_iterator it = l.begin();
        while (it != l.end())
        {
            cout << *it << ' ';
            ++it;
        }
        cout << endl;
    }

///

    // 测试无参构造、n个val的构造、迭代器区间构造
    void test_list1()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);
        l.push_back(4);
        l.push_back(5);

        list<int> l1(10, 20);
        list<int> l2(++l1.begin(), --l1.end());

        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;

        for (auto e : l1)
        {
            cout << e << ' ';
        }
        cout << endl;

        for (auto e : l2)
        {
            cout << e << ' ';
        }
        cout << endl;
    }

    // 测试 insert push_back push_front
    // 测试 iterator 范围for
    // 测试 operator !=  operator* 
    void test_list2()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);
        l.push_back(4);
        l.push_back(5);
        l.push_front(10);
        l.push_front(20);


        list<int>::iterator lit = l.begin();
        while (lit != l.end())
        {
            cout << *lit << ' ';
            ++lit;
        }
        cout << endl;

        for (auto& e : l)
        {
            e += 10;
            cout << e << ' ';
        }
        cout << endl;
    }

    // 测试 erase pop_back pop_front
    void test_list3()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);
        l.push_back(4);
        l.push_back(5);

        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;

        l.pop_back();
        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;

        l.pop_front();
        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;
    }

    // 测试 operator++  operator++(int)
    // 测试 operator--  operator--(int)
    void test_list4()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);
        l.push_back(4);
        l.push_back(5);

        list<int>::iterator lit1 = l.begin();
        cout << *(lit1++) << endl;
        cout << *(++lit1) << endl;

        list<int>::iterator lit2 = l.end();
        cout << *(--lit2) << endl;
        cout << *(lit2--) << endl;
        cout << endl;
    }

    // 测试 operator==  operator!=
    void test_list5()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);
        l.push_back(4);
        l.push_back(5);

        list<int>::iterator lit = l.end();
        cout << (lit == lit) << endl;
        cout << (lit != lit) << endl;
        cout << endl;
    }

    void test_list6()
    {
        list<int> l;
        l.push_back(1);
        l.push_back(2);
        l.push_back(3);

        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;
        cout << l.front() << ' ' << l.back() << endl;

        l.pop_back();
        l.pop_front();

        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;
        cout << l.front() << ' ' << l.back() << endl;

        l.pop_back();
        l.pop_front();

        for (auto e : l)
        {
            cout << e << ' ';
        }
        cout << endl;
        cout << l.front() << ' ' << l.back() << endl;
    }

    // 测试 operator->
    void test_list7()
    {
        list<AA> l1;
        l1.push_back(AA(1, 1));
        l1.push_back(AA(2, 2));
        l1.push_back(AA(3, 3));
        l1.push_back(AA(4, 4));

        list<AA>::iterator it = l1.begin();
        while (it != l1.end())
        {
            cout << it->_a1 << ' ' << it->_a2 << endl;
            ++it;
        }
    }

    // 测试拷贝构造和赋值重载  
    void test_list8                                                                      ()
    {
        list<int> l1;
        l1.push_back(1);
        l1.push_back(2);
        l1.push_back(3);
        l1.push_back(4);

        // 拷贝构造l2
        list<int> l2(l1);

        // 输出l1和l2的值
        for (auto e : l1)
        {
            cout << e << ' ';
        }
        cout << endl;

        for (auto e : l2)
        {
            cout << e << ' ';
        }
        cout << endl;

        // l2中的值都*10,并输出
        for (auto& e : l2)
        {
            e *= 10;
            cout << e << ' ';
        }
        cout << endl;

        // 将l2赋值给l1
        l1 = l2;

        // 输出l1和l2的值
        for (auto e : l1)
        {
            cout << e << ' ';
        }
        cout << endl;

        for (auto e : l2)
        {
            cout << e << ' ';
        }
        cout << endl;
    }

    // 测试print_container
    void test_list9()
    {
        list<int> l1;
        l1.push_back(1);
        l1.push_back(2);
        l1.push_back(3);
        l1.push_back(4);

        print_container(l1);

        list<string> l2;
        l2.push_back("1111111111111111111");
        l2.push_back("2222222222222222222");
        l2.push_back("3333333333333333333");
        l2.push_back("4444444444444444444");

        print_container(l2);

        vector<string> v;
        v.push_back("1111111111111111111");
        v.push_back("2222222222222222222");
        v.push_back("3333333333333333333");
        v.push_back("4444444444444444444");
        print_container(v);
    }

    void test_list10()
    {
        list<int> l1;
        l1.push_back(1);
        l1.push_back(2);
        l1.push_back(3);
        l1.push_back(4);

        list<int>::reverse_iterator it = l1.rbegin();
        while (it != l1.rend())
        {
            cout << *it << ' ';
            ++it;
        }
        cout << endl;
    }
};



四、 list 与 vector 的对比

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

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

结尾

如果有什么建议和疑问,或是有什么错误,大家可以在评论区中提出。
希望大家以后也能和我一起进步!!🌹🌹
如果这篇文章对你有用的话,希望大家给一个三连支持一下!!🌹🌹
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/567092.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

idea配置推荐插件详细讲解

配置插件是为了在开发过程中提高效率、改善开发体验而安装的。在IntelliJ IDEA中&#xff0c;你可以按照以下步骤配置插件&#xff1a; 打开插件配置页面&#xff1a; ● 在顶部菜单栏中选择 “File” -> “Settings”&#xff08;或者使用快捷键 Ctrl Alt S&#xff09;…

相亲平台app小程序

相亲平台app小程序是一种基于手机应用的微型程序&#xff0c;专为在线相亲交友活动设计。它提供了一系列的功能&#xff0c;旨在帮助用户更方便、更高效地找到心仪的伴侣。 首先&#xff0c;用户可以在个人资料部分上传照片、填写个人资料、设置兴趣爱好等信息&#xff0c;以便…

【行为型模型】迭代器模式

一、迭代器模式概述 迭代器模式定义&#xff1a;提供一种方法顺序访问一个聚合对象中的各个元素&#xff0c;而又不暴露其内部的表示。把游走的任务放在送代器上&#xff0c;而不是聚合上。这样简化了聚含的接口和实现,也让责任各得其所。(对象行为型) 迭代器模式的优缺点&…

uni-app开发canvas绘图画画,记录每一步画的信息, 并实现后退功能

在uni-app中&#xff0c;要实现canvas绘图并记录每一步的信息以实现后退功能&#xff0c;你需要做几件事&#xff1a; 初始化Canvas上下文&#xff1a;首先&#xff0c;你需要在页面加载时初始化canvas上下文。 记录绘图步骤&#xff1a;在绘图过程中&#xff0c;你需要记录每…

20240416,深拷贝浅拷贝,对象初始化和清理,对象模型和THIS指针

哈哈哈乌龟越狱了 目录 2.5 深拷贝&浅拷贝 2.6 初始化列表 2.7 类对象作为类成员 2.8 静态成员 2.9 成员变量和成员函数分开存储 2.10 THIS指针的用途 2.11 空指针访问成员函数 2.12 COSNT修饰成员函数 2.5 深拷贝&浅拷贝 浅拷贝&#xff1a;简单的赋值拷贝…

揭秘分销系统:商业模式的新风向

大家好&#xff0c;我是微三云周丽&#xff0c;今天给大家分析当下市场比较火爆的商业模式&#xff01; 小编今天跟大伙们分享什么是分销系统&#xff1f; 在数字化浪潮席卷全球的今天&#xff0c;电子商务以其独特的优势&#xff0c;正在重塑商业世界的格局。其中&#xff0…

css设置输入框边框无效或者不展示边框

bug描述&#xff1a;在聚焦的时候&#xff0c;期望输入框的边框是主题色&#xff0c;但是不知道是个啥颜色。 发现输入框input以及textarea样式css标签:focus更改样式无效这个问题。 若希望实现input在触发焦点时更改样式&#xff0c;通常会想到使用:focus选择器&#xff0c;…

积极探索新质生产力,九河云携手华为云技术交流引领数智跃迁

4月18日&#xff0c;九河云携手华为云举办了华为云SA技术培训会议&#xff0c;培训邀请到华为云技术人员作为主讲人&#xff0c;通过理论讲解与案例结合的方式&#xff0c;围绕ECS和EBS之间的联动&#xff0c;调优和数据保护等方面展开&#xff0c;深入浅出地讲解了基于EBS部署…

uniapp 引用组件后 不起作用 无效果 不显示

根据uniapp官方文档easycom组件规范 只要组件安装在项目的components目录下或uni_modules目录下&#xff0c;并符合components/组件名称/组件名称.(vue|uvue)目录结构&#xff08;注意&#xff1a;当同时存在vue和uvue时&#xff0c;uni-app 项目优先使用 vue 文件&#xff0c;…

浅谈防火墙,IPS,APT威胁检测的互补性

在学习网络安全产品时发现很多产品的目的与功能大同小异都是防范非法流量或威胁&#xff0c;但是既然有产品的差异就有作用的目的的差异&#xff0c;下面浅谈一下三个网络安全产品的差异化与互补点 防火墙 传统防火墙主要是工作在二到四层&#xff0c;不会对报文的载荷进行检…

App Cleaner Uninstaller中文激活版:mac最强深度清理软件

App Cleaner & Uninstaller 是一款适用于 Mac 操作系统的软件应用程序&#xff0c;允许用户轻松卸载不需要的应用程序、删除剩余文件和文件夹以及管理启动项。该应用程序会分析与您要删除的应用程序关联的文件&#xff0c;并帮助识别其所有组件&#xff0c;以便您可以一次将…

中红医疗:纷享销客CRM系统如何助力​数字化“狂飙”

纷享销客深耕 CRM 多年&#xff0c;可以顺畅打通 CRM 和 ERP 系统客户资源池&#xff0c;将金蝶苍穹平台的物料、产品基础主数据作为档案同步到纷享销客&#xff0c;以便商务维护好产品及库存。 纷享销客通过成熟的集成方案提高系统耦合性&#xff0c;让销售实时获得新产品及营…

JsonPath实战

概述 JsonPath&#xff0c;GitHub是一种简单的方法来提取给定JSON文档的部分内容&#xff0c;提供类似正则表达式的语法来解析JSON文档。 特性 入门 引入如下Maven依赖&#xff1a; <dependency><groupId>com.jayway.jsonpath</groupId><artifactId&…

用Python将原始边列表转换为邻接矩阵

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 在图论和网络分析中&#xff0c;图是一种非常重要的数据结构&#xff0c;它由节点&#xff…

驱动比例换向阀放大器

比例换向阀放大器技术是电液比例系统中关键的组成部分&#xff0c;它主要用于控制比例阀&#xff0c;实现对液压流量或压力的精确控制。 高精度控制&#xff1a;通过比例阀放大器&#xff0c;系统可以非常精确地调节液压流量或压力&#xff0c;这对于要求精密操作的机械系统来说…

DSP系统的设计过程与选型

DSP的设计步骤分几个阶段&#xff0c;应用系统的设计过程如图所示。 技术指标的确定 器件的选型原则 其他因素的考虑

学习c语音的自我感受

因为是自学&#xff0c;所以走过不少弯路。去年&#xff0c;受知乎“python性能弱”风潮的影响&#xff0c;学过go,rust。 在学习这些新语言的时候&#xff0c;由衷感受到&#xff0c;或是本身侧重方向的原因&#xff08;如go侧重服务器&#xff09;&#xff0c;或是语言太新不…

Php-WebView 现代跨平台 GUI分享

GitHub :php-webview 一个用于 C/C 的小型跨平台 Web 视图库&#xff0c;用于构建现代跨平台 GUI。 该项目的目标是为最广泛使用的平台创建一个通用的 HTML5 UI 抽象层。 它支持双向 JavaScript 绑定&#xff08;从 C/C 调用 JavaScript 和从 JavaScript 调用 C/C&#xff09;。…

蛋白质致病突变的计算方法(四)

3.1.5 域定位 (domain location) 残基在序列中的位置可分为N-terminal(1-30%)、中间(31-70%)和C-terminal(71-100%)。Singh等人报告称&#xff0c;TP53的中心和高度保守的DNA结合域包含一簇体细胞错义突变&#xff0c;包括R175、G245、R248和R273。这些突变形成与DNA的直接接触…

Docker 部署 WordPress 并完成建站

什么是 WordPress WordPress 是使用 PHP 语言开发的博客平台&#xff0c;用户可以在支持 PHP 和 MySQL 数据库的服务器上架设属于自己的网站。也可以把 WordPress 当作一个内容管理系统&#xff08;CMS&#xff09;来使用。WordPress 是一款个人博客系统&#xff0c;并逐步演化…