I was responding to a std :: stack implementation problem. It was easy, but I could not use my first idea: std :: vector (it replaced forever the dynamic pointers). My code is:
template <class T> class stack
{
T* data;
unsigned size_;
public:
stack() : size_(0){}
stack(T initializer, unsigned times)
{
size_ = times;
data = new T[times];
for(int i = 0; i < times; i++) data[i] = initializer;
}
void push(T data_)
{
size_++;
data = new T[size_];
data[size_-1] = data_;
}
void pop()
{
size_--;
data = new T[size_];
}
T top() const
{
return data[size_-1];
}
void clear()
{
for(unsigned i = 0; i < size_; i++)
{
data[i] = 0;
}
}
bool empty() const
{
bool ret = true;
for(unsigned i = 0; i < size_; i++)
{
if(data[i] != 0)
{
ret = false;
break;
}
}
return ret;
}
unsigned size() const
{
return size_;
}
void resize(unsigned newsize)
{
size_ = newsize;
data = new T[size_];
}
};
I decided to test with an integer; and it worked. However, I did one of size 2 and decided to test the pop method.
int main()
{
stack<unsigned> A;
A.push(10);
A.push(2);
std::cout << A.top() << "\n";
A.pop();
std::cout << A.top();
}
There, the top method returns garbage. What am I doing wrong?