list的const迭代器的实现

要实现const迭代器首先要实现普通迭代器,普通迭代器主要是要实现他的解引用、后置加加等操作符,他的底层是指针,但是不是原生指针,是通过用一个类进行封装,通过对类进行传参数来解决问题,先定义链表的结点

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

};

接下来是实现list类

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;

	list()
	{
		_head = new Node;
		_head->_prev = _head;
		_head->_next = _head;
	}
	~list()
	{
		clear();
		delete _head;
		_head = nullptr;
	}
	iterator begin()
	{
		return iterator(_head->_next);
	}
	iterator end()
	{
		return iterator(_head);
	}
	const_iterator begin()const
	{
		return const_iterator(_head->_next);
	}
	const_iterator end()const
	{
		return const_iterator(_head);
	}
	private:
		Node* _head;
};

在这里面我用了三个模板参数去传递,这为之后定义const迭代器埋下了伏笔,接下来实现普通迭代器

	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)
		{}
		//*it
		Ref operator*()
		{
			return _node->_val;
		}
		//++it
		Self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		//it++
		Self operator++(int)
		{
			Self tmp = *this;
			//_node = _node->_next;
			++(*this);
			return tmp;
		}
		Self& operator--()
		{
			_node = _node->_prev;
			return *this;

		}
		Self operator--(int)
		{
			Self tmp = *this;
			//_node = _node->_prev;
			--(*this);
			return tmp;
		}
		Ptr operator->()
		{
			return &_node->_val;
		}
		bool operator!=(const Self& it)
		{
			return _node != it._node;
		}

	};

在这个迭代器类中,我们定义了三个模板参数,其中第一个是为了传递list存放数据的类型,接下来两个是为了定义接下来的const迭代器在通过list代码中我们可以知道const迭代器传了两个const对象过去,通过传const对象去获得const迭代器,并且通过返回值来是返回的也是const对象,这就是const迭代器的封装类。

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值