C++STL基础及应用第27页

来源:互联网 发布:java maven 配置 编辑:程序博客网 时间:2024/05/18 02:10

C++STL基础与应用第27页中的代码,如下:

#include <iostream>#include <iterator>#include <ostream>using namespace std;template<class T>class MyLink{public:   struct Unit      {         T value;  Unit * next;       };       class LinkIterator       {         Unit * init;         public:           LinkIterator(Unit *init)           {           this->init= init;             }          bool operator !=(LinkIterator& t)          {           return this->init!=t.init;           }           void operator ++(int)           {           init = init->next;              }           Unit  operator * ()           {           return  *init;              }       };       Unit * head;       Unit * tail;       Unit * prev;    public:       MyLink()       {          head = tail = prev = NULL;       }       void add(T & value)       {             Unit * u = new Unit();  u->value = value;  u->next  = NULL;  if(head == NULL)  {       head = u; prev = u;    }    else    {     prev->next = u;     prev = u;    }    tail = u->next;          }          Unit * Begin()          {            return head;          }          Unit * End()          {            return tail;          }          virtual ~MyLink()          {            if(head != NULL)            {               Unit * prev = head;  Unit * next = NULL;  while(prev != tail)  {       next = prev->next; delete prev; prev = next;    }                 }          }         };//template <class T> //这句不能用//ostream & operator << (ostream & os, MyLink<T>::LinkIterator s)//这句也要改成如下ostream & operator << (ostream & os, MyLink<int>::LinkIterator s){    os << (*s).value ;    return os;}template<class Init>void display(Init S,Init E){    cout << endl;    for(Init mid = S; mid!=E; mid++)    {         cout << mid <<"\t";    }    cout <<endl;}int main(int argc, char *argv[]){       int m=0; MyLink<int> ml;       for(int i=0;i<5;i++)       {         m = i+1; ml.add(m);       }       MyLink<int> ::LinkIterator s(ml.Begin());       MyLink<int> ::LinkIterator e(ml.End());      display(s,e);      return 0;}


0 0
原创粉丝点击