Topic of this issue: Implementation of reverse iterator in STL
Blog homepage: Xiaofeng
Share what you have learned and the problems you have encountered
The ability of the editor is limited, and if there are mistakes, I hope everyone will give me a lot of help.
1. Reverse iterator
Reverse iterator, let's think about it. At the beginning, we implemented the forward iterator by using class templates or directly using native pointers. Copy
a copy of the iterator we wrote before, and then ++ becomes -- , - - Change to ++.
We will find that when this is implemented, each container has to write such a thing. The code is very redundant.
So we implement a general reverse iterator, that is, if there is a forward iterator, directly adapt to the Our reverse iterator.
![](https://img-blog.csdnimg.cn/img_convert/e1aa99eb775e32b80a2eead6638cf936.jpeg)
Is there any other way?
We can use the adapter directly to adapt the forward iterator to a reverse iterator. That's it.
2. Source code
With the big idea, get started directly.
The implementation process is analyzed.
//反向迭代器的适配器 。
namespace zxf
{
//调用的时候,一般都是在别的类内部使用,供别的类调用
//typedef reverse_iterator<iterator> reverse_iterator;
//typedef reverse_iterator<const_iterator> const_reverse_iterator;
//这里就是使用 iterator 适配 reverse_ierator
//使用const_iterator 适配 const_reverse_iterator
template<class iterator, class ref, class ptr>
class reverse_iterator
{
public:
typedef reverse_iterator<iterator, ref, ptr> self;
//迭代器在定义的时候 必须初始化。
reverse_iterator(const iterator it)
:_it(it)//注意只能写在初始化列表中,不能写在函数体内部
//_it是一个正向迭代器,迭代器在创建的时候必须初始化。
{}
self operator++(){
--_it;
return *this;
}
self operator--(){
++_it;
return *this;
}
//iterator也是一个类模板,它是对 pnode(node*)(list就是节点的指针,vector就是元素的指针) 的封装
//iterator知道数据类型,但是reverse_iterator不知道数据类型。
ref operator*(){//这就是为啥要给出第二个模板参数的原因之一:
//我们无法知道iterator类模板成员变量指向的元素的类型,所以要把那个元素的类型传过来。
//另一个原因就是区分开我们的const反向迭代器和正常反向迭代器。
iterator tmp = _it;
return *(--tmp);
//这里'--'的原因就是我们在设置反向迭代器的rbegin() 和 rend()是怎么实现的
//这就是一个边界的问题,和 rbegin() ,rend() 结合看的。
//假如你改变 自己实现的 rbegin() ,rend() 也可以不 '--'。
}
bool operator!=(const self& it)//这里引用可加可不加
{
return _it != (it._it);
}
private:
iterator _it;//底层的正向迭代器。
};
}
3. What is the meaning of the reverse iterator?
The key point is reuse. The reverse iterator here is not written for a certain container, but for all containers.
As long as a container has a forward iterator, it can be adapted to a reverse iterator.
Code repetition The usability is very good, and it is a very essential part of STL.