Stack iterator



  • Hallo,

    ich habe eine generische Stack-Klasse geschrieben und möchte jetzt gern einen Iterator hinzufügen. Leider funktioniert es nicht so wie ich mir es vorstelle. Ich hab schon verschiedenes ausprobiert und auch das Google-Orakel befragt.

    So stell ich mir das vor:

    template <class T> class TStack
    {
    public:
        class iterator
        {
        private:
            TStack<T> _stack;
    
        public:
            iterator()
            {
            }
            ~iterator()
            {
            }
        };
    
    private:
        struct node {
            T _key;
            node* _next;
        };
    
        node* _head;
        node* _tail;
    
    public:
        TStack()
        {
            _head = new node;
            _tail = new node;
            _head->_next = _tail;
            _tail->_next = (node *)0;
        }
    
        virtual ~TStack()
        {
            Erase();
            delete _head;
            delete _tail;
        }
    
        void Push(T x)
        {
            node *tmp = new node;
            tmp->_key = x;
            tmp->_next = _head->_next;
            _head->_next = tmp;
        }
    
        void Pop(T& x)
        {
            if (IsEmpty()) {
                throw new TStackException();
            }
            node *tmp = _head->_next;
            x = tmp->_key;
            _head->_next = tmp->_next;
            delete tmp;
        }
    
        T Pop()
        {
            if (IsEmpty()) {
                throw new TStackException();
            }
            node *tmp = _head->_next;
            T x = tmp->_key;
            _head->_next = tmp->_next;
            delete tmp;
            return x;
        }
    
        T Top()
        {
            if (IsEmpty()) {
                throw new TStackException();
            }
            T x = _head->_next->_key;
            return x;
        }
    
        int IsEmpty() const {
            return (_head->_next == _tail);
        }
    
        void Erase()
        {
            while (!IsEmpty()) {
                node *tmp = _head;
                _head = _head->_next;
                delete tmp;
            }
        }
    };
    

    Der Compiler sagt dazu ...
    e:\entwicklung\calc\stack.h(12) : error C2079: '_stack' verwendet undefiniertes class 'TStack<int>'

    Kann mir jemand sagen, wie und wo ein simpler Iterator für TStack deklariert werden muss?

    Miles



  • Warum soll der Iterator denn einen Stack enthalten? Mach mal eine Referenz daraus ...

    Dazu: Einen Stack kann man nicht sinnvoll iterieren, dann isses kein Stack mehr
    und: mach die Pop Methode lieber so, dass sie void zurückgibt, wenn du eine Top-Methode hast.



  • Bashar,

    danke für deine Tips. Du hast mir sehr geholfen. Was den Iterator angeht, hast du natürlich recht. Der ist für einen Stapel nicht sinnvoll.

    Miles


Anmelden zum Antworten