迭代器的设计原则
在上一节4、list深度探索_努力的小带土的博客-CSDN博客讲解list的时候,观察仔细的小伙伴一定注意到了,下面代码中五个typedef是迭代器中必不可少的组成部分。
template<class T, class Ref, class Ptr>
struct __list_iterator{
//所有的迭代器都要有这5个typedef
typedef bidirectional_iterator_tag iterator_category;//(1)
typedef T value_type;//(2)
typedef Ptr pointer;//(3)
typedef Ref reference;//(4)
typedef ptrdiff_t difference_type;//(5)
.......
}
那么它们到底起到什么作用呢?作用即是回答程序算法的疑惑。在算法程序中,往往都少不了对所调用容器进行属性详解,那么程序是如何知道你所调用容器是什么属性呢?就是通过上述迭代器中的五个typedef,那么算法是怎么使用它们的呢?看下述代码你便知晓。
template<calss I,class I>
inline void algorithm(I first,I last)
{
....
I::iterator_category;
I::value_type;//(2)
I::pointer;//(3)
I::reference;//(4)
I::difference_type;//(5)
}
上述代码,通过直接调用迭代器中的type来获取容器中的相关信息。