@shevzoom
 dev., student at MEPhI

Как победить бесконечный цикл?

Бесконечно выводит число 31 (пометил коментами место), в чем ошибка?
#include <iostream>
#include <string>
#include <exception>
using namespace std;

template <class T>
class TStack {
    struct Elem {
        T data;
        Elem *next;

        Elem(const T &d, Elem *p)
                : data(d), next(p) {}
    };
    Elem *Head;
    int count;
    TStack(const TStack &);
    TStack &operator=(const TStack &);
public:
    class Error : public std::exception {};
    TStack() ;
    ~TStack() ;
    void push(const T &d);
    T top() const ;
    T pop();
    bool empty() const ;
    int counter() const ;
};
template < class T >
TStack<T>::TStack(): Head(0), count(0){ }
template < class T >
TStack<T>::~TStack() {
    while (!empty()) {T t = pop();}
}
template < class T >
void TStack<T>::push(const T& d){
    Head = new Elem(d, Head);
    ++count;
}
template < class T >
T TStack<T>::top() const {
    if (!empty()) return Head->data;
    else throw Error();
}
template < class T >
T TStack<T>::pop() {
    if(!empty())  throw Error();
    T top = Head->data;
    Elem *oldHead = Head; Head = Head->next;
    delete oldHead;
    --count;
    return top;
}
template < class T >
bool TStack<T>::empty() const {return Head == 0;}
template < class T >
int TStack<T>::counter() const { return count;}

int main() {
    TStack<double> t;
    t.push(11);
    t.push(21);
    t.push(31);
    cout << t.counter() << endl;
    while (!t.empty()) {                // бесконечно 31
        cout << t.top() << endl;     //
        double p = t.top();
    }
    cout << t.counter() << endl;

    TStack<string> S;
    S.push("one");
    S.push("two");
    S.push("three");
    cout << S.counter() << endl;
    while (!S.empty()) {
        string p = S.pop();
        cout << p << endl;
    }
    cout << S.counter() << endl;
    try { string p = S.pop(); }
    catch(const exception &e) { cout << e.what() << endl; }
    system("PAUSE");
    return 0;
    }
  • Вопрос задан
  • 188 просмотров
Решения вопроса 1
@KingstonKMS
Так он и будет циклически работать. Вы элементы не извлекаете(удаляете) из массива
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы