C++ STL容器系列(二):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常见接口的使用

2.1 list的构造函数

void TestList1()
{
    list<int> l1;                         // 构造空的l1
    list<int> l2(4, 100);                 // l2中放4个值为100的元素
    list<int> l3(l2.begin(), l2.end());  // 用l2的[begin(), end())左闭右开的区间构造l3
    list<int> l4(l3);                    // 用l3拷贝构造l4

    // 以数组为迭代器区间构造l5
    int array[] = { 16,2,77,29 };
    list<int> l5(array, array + sizeof(array) / sizeof(int));

    // 列表格式初始化C++11
    list<int> l6{ 1,2,3,4,5 };

}

2.2 list iterator的使用

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

void TestList2()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));
    // 使用正向迭代器正向list中的元素
    // list<int>::iterator it = l.begin();   // C++98中语法
    auto it = l.begin();                     // C++11之后推荐写法
    while (it != l.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    // 使用反向迭代器逆向打印list中的元素
    // list<int>::reverse_iterator rit = l.rbegin();
    auto rit = l.rbegin();
    while (rit != l.rend())
    {
        cout << *rit << " ";
        ++rit;
    }
    cout << endl;
}

注意:

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

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

2.3 list 元素访问与容量接口

list不支持任意位置的随机访问 ,因此只提供了front和back接口来访问首尾元素,其他元素的访问需要迭代器++或--操作。

 2.4 list 元素修改

void PrintList(const list<int>& l)
{
    // 注意这里调用的是list的 begin() const,返回list的const_iterator对象
    for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
    {
        cout << *it << " ";
        // *it = 10; 编译不通过
    }

    cout << endl;
}

// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{
    cout << "list的头插头删和尾插尾删" << endl;
    int array[] = { 1, 2, 3 };
    list<int> L(array, array + sizeof(array) / sizeof(array[0]));

    // 在list的尾部插入4,头部插入0
    L.push_back(4);
    L.push_front(0);
    PrintList(L);

    // 删除list尾部节点和头部节点
    L.pop_back();
    L.pop_front();
    PrintList(L);
}

// insert /erase 
void TestList4()
{
    cout << "list任意位置的插入和删除" << endl;
    int array1[] = { 1, 2, 3 };
    list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));

    // 获取链表中第二个节点
    auto pos = ++L.begin();
    cout << *pos << endl;

    // 在pos前插入值为4的元素
    L.insert(pos, 4);
    PrintList(L);

    // 在pos前插入5个值为5的元素
    L.insert(pos, 5, 5);
    PrintList(L);

    // 在pos前插入[v.begin(), v.end)区间中的元素
    vector<int> v{ 7, 8, 9 };
    L.insert(pos, v.begin(), v.end());
    PrintList(L);

    // 删除pos位置上的元素
    L.erase(pos);
    PrintList(L);

    // 删除list中[begin, end)区间中的元素,即删除list中的所有元素
    L.erase(L.begin(), L.end());
    PrintList(L);
}

 2.5 list 迭代器失效

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

三、list的模拟实现

3.1 list节点的定义

	template<class T>
	struct ListNode {
		ListNode<T> * _next;//指向下一个节点的指针
		ListNode<T> * _prev;//指向前一个节点的指针
		T _data;//节点的数据
		ListNode(const T& x=T())
			:_next(nullptr)
			,_prev(nullptr)
			,_data(x)
		{}
	};

3.2 list迭代器的封装

由于list的底层空间不连续,其迭代器++或--等运算符需要重载。所以不可以直接使用原生指针(直接定义出来的指针)typedef后作为迭代器。需要对原生指针进行封装,并重载运算符

template <class T,class Ref,class Ptr>
	struct __list_iterator {
		typedef ListNode<T> Node;
		typedef __list_iterator<T, Ref, Ptr> self;
        //这里的Ref和Ptr分别为operator*()和operator->()的返回值类型

		Node* _node;//迭代器的本质是结点指针
		__list_iterator(Node* x)
			:_node(x)
		{}

		//++it
		self& operator++() {
			_node = _node->_next;//让_node指向下一个节点
			return *this;
		}

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

		self& operator--() {
			_node = _node->_prev;//让_node指向前一个节点
			return *this;
		}

		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;
		}

	};

这里list迭代器类模板传递了三个参数,通过对三个参数的控制来实现迭代器的泛型编程,如下:

typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<const T, const T&, const T*> const_iterator;

传递const类型时会实例化为const_iterator,利用迭代器*和->访问元素时不可修改。

3.3 list完整代码实现

template<class T>
struct ListNode {
	ListNode<T>* _next;
	ListNode<T>* _prev;
	T _data;
	ListNode(const T& x = T())
		:_next(nullptr)
		, _prev(nullptr)
		, _data(x)
	{}
};

template <class T, class Ref, class Ptr>
struct __list_iterator {
	typedef ListNode<T> Node;
	typedef __list_iterator<T, Ref, Ptr> self;

	Node* _node;
	__list_iterator(Node* x)
		:_node(x)
	{}


	//++it
	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;
	}

	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>
class list {
	typedef ListNode<T> Node;
public:
	typedef __list_iterator<T, T&, T*> iterator;
	typedef __list_iterator<const T, const T&, const 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;
	}

	list() {
		empty_init();
	}

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

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

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

	}

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

	list<T>& operator=(list<T> lt) {
		swap(lt);
		return *this;
	}

	void push_back(const T& x) {
		/*Node* newnode = new Node(x);
		Node* tail = _head->_prev;

		tail->_next = newnode;
		newnode->_prev = _tail;
		newnode->_next = _head;
		_head->_prev = newnode;*/
		insert(end(), x);

	}

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

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

	void pop_front() {
		erase(begin());
	}
	//prev newnode cur
	iterator insert(iterator pos, const T& x) {
		Node* cur = pos._node;
		Node* prev = cur->_prev;
		Node* newnode = new Node(x);
		prev->_next = newnode;
		newnode->_prev = prev;
		newnode->_next = cur;
		cur->_prev = newnode;
		return newnode;
	}

	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 next;
	}

private:
	Node* _head;
};

  • 16
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值