Answer the question
In order to leave comments, you need to log in
How to beat the infinite loop?
Infinitely displays the number 31 (marked the place with comments), what is the error?
#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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question