3
I was responding to an implementation problem of Std::stack. It was easy, but I couldn’t use my first idea: Std::vector (replaced dynamic pointers forever). 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 a 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();
}
Then the top method returns trash. What I’m doing wrong?
You’re allocating a new vector to each push, and you’re not copying the values. You’re not freeing the memory either. And it’s also mixing the size of the stack with its capacity with the zeroed elements. I think that’s it :-)
– C. E. Gesser
I agree with @C.E.Gesser. And don’t forget to create a destructor
~stack()
for your class. Yes, even if you move right intopush()
andpop()
, you should also try to free up memory in the destructor.– Lucas Lima
@C.E.Gesser Can you put this in the answer and "fix it" for me? I have the problems, but I don’t have the answers :(.
– user2692