List的迭代器

来源:互联网 发布:10月份信贷数据 编辑:程序博客网 时间:2024/04/29 10:25

引自"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 !(*this == rhs); }private:    iNode *inode_ptr;  };    Iterator begin()  {    return Iterator(list_head);  }  Iterator end()  {    return Iterator(list_tail);  }      //构造  List()  {    list_head = list_tail = NULL;  }  //析构  ~List()  {    clear();  }    //在链表尾部添加一个元素  iNode * push_back(TYPE &val)                       {      middle_ptr=new iNode();    middle_ptr->data=val;    middle_ptr->next=NULL;    if (list_head==NULL)    {      list_head=list_tail=middle_ptr;    }    else    {      list_tail->next=middle_ptr;      list_tail=middle_ptr;    }    return list_head;  }  //清除链表  void clear()  {    while(NULL != list_head)    {  delete list_head;  list_head = list_head->next;    }  list_tail = NULL;  }      private:  iNode *list_head,*list_tail,*middle_ptr;};struct sTestData{  int a;  char b;};void test_myList(){  List<sTestData> testList;  for(int i = 0;i<=8;i++)  {    sTestData testdata;testdata.a = i;testdata.b = 'b';    testList.push_back(testdata);  }      for (List<sTestData>::Iterator itr=testList.begin();itr!=testList.end();itr++)  {cout<<itr->a<<" "<<itr->b<<endl;  }    testList.clear();   }int main(){     test_myList();  return 1;}


 

 

0 0