引自"C++ primer plus 6"中的话:
理解迭代器是理解STL的关键所在。
模板使得算法独立于存储的数据类型,而迭代器使算法独立于使用的容器类型。
因此,它们都是STL通用方法的重要组成部分。
一直觉得迭代器很神秘,在调试了简单的List迭代器之后,才认识到迭代器实质上就是遍历访问容器里面的元素。不同的容器,它的遍历方式不同,迭代器也就各不相同。
数组下标的移动和指针的++就是最简单的迭代。
#include <iostream>
using namespace std;
template <typename TYPE>
class List
{
public:
//链表结点
struct iNode
{
TYPE data;
iNode* next;
};
class Iterator
{
public:
Iterator(iNode *ptr):inode_ptr(ptr)
{
}
void operator++(int)
{
inode_ptr = inode_ptr->next;
}
TYPE* operator->()
{
return &(inode_ptr->data);
}
TYPE& operator*()
{
return inode_ptr->data;
}
bool operator==(const Iterator& rhs ) const
{
return inode_ptr == rhs.inode_ptr;
}
bool operator!=(const Iterator& rhs) const
{
return !