Раздел «Алгоритмы».ListTemplateExample:

Пример шаблона list

#include <iostream>
#include <stdlib.h>

namespace mylib {

template <typename T> 
class list {

   typedef struct list_item {
      struct list_item *next;
      T value;
   } litem_t;
   
private:
   litem_t *head_item;
   litem_t end_item;

public:
   class iterator {
   private:
      litem_t *li;
   public:
      iterator() {
         li = NULL;
      }
      iterator(litem_t *a) {
         li = a;
      }
      iterator& operator ++() {
         li = li->next;
         return *this;
      }
      iterator operator ++(int) {
         iterator res = *this;
         li = li->next;
         return res;
      }

      bool operator ==(const iterator& a) {
         return li == a.li ;
      }
      bool operator !=(const iterator& a) {
         return li != a.li ;
      }
      T& operator*() {
         return li->value;
      }
    };
    
   list(void) {
      head_item = &end_item;
      end_item.next = &end_item;
   }
   ~list(void) {
      for(litem_t *li = head_item; li != &end_item ; ) {
          litem_t *tmp = li->next;
          delete li;
          li = tmp;
      } 
      head_item = &end_item;
   }
      
   iterator end(void) {
      return iterator(&end_item);
   }
   iterator begin(void) {
      return iterator(head_item);
   }
   void push(T x) {
      litem_t *li = new litem_t;
      li->next = head_item;
      li->value = x;
      head_item = li; 
   }
   
};

};

using namespace mylib;

int main(int argc, char *argv[])
{
   list<int> a;

   for( int i = 0; i < 100; i++) {
      a.push(i);
   }

   for(list<int>::iterator it = a.begin(); it != a.end() ; it++) {
      printf("%d\n", *it);

   }

   system("PAUSE");   
   return 0;
}
AlgorithmClasifyForm
Type: Код
Scope: STL
Strategy:  
Language: C++
Complexity: Medium