List的迭代器

引自"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;
}


 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值