[英]Stack implementation using array C++
我正在嘗試實現 class “堆棧”的一些方法。 對於 push() 方法,如果堆棧頂部等於容量,我試圖復制數組的容量。 頂部是下一個插槽的項目。 我通過創建一個容量是原始數組兩倍的新數組然后復制內容來做到這一點。 我實現的所有其他方法(empty()、pop()、top())似乎工作正常,但如果堆棧有超過 10 個元素,則推送 function 出於某種原因打印堆棧的前 4 個項目的隨機值(必須增加容量)。 為什么會出現這個問題?
#include <iostream>
using namespace std;
class stack
{
public:
stack();
bool empty();
void pop();
void push(int x);
int &topElem();
private:
int *buffer;
int top; // Top element of stack
int capacity = 10; // Capacity of array
};
stack::stack()
{
int *val = new int[capacity];
buffer = val;
top = 0;
}
bool stack::empty()
{
if(top == 0)
return true;
else
return false;
}
void stack::push(int x)
{
if(top == capacity)
{
int *newArray = new int[capacity * 2];
for(int i = 0; i < capacity; i++)
{
newArray[i] = buffer[i];
//cout << "newArray[" << i << "]: " << newArray[i] << endl;
}
buffer = newArray;
delete[] newArray;
newArray = NULL;
}
buffer[top] = x;
top++;
}
void stack::pop()
{
if(!empty())
{
top--;
}
else
cout << "Stack is empty!" << endl;
}
int& stack::topElem()
{
return buffer[top - 1];
}
int main()
{
stack plates;
for (int i = 0; i < 20; i++) // Add 20 elements to the stack
{
plates.push(i);
}
while (!plates.empty())
{
cout << plates.topElem() << endl; // Prints the elemtents of the stack
plates.pop(); // Pops the last element of the stack
}
return 0;
}
// Output 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 393 -1250224288 393 -1250206816
buffer = newArray;
delete[] newArray;
這不符合您的期望。 它將buffer
指向新數組,泄漏舊數組,然后刪除緩沖區指向的 memory。
你可能想要這樣的東西:
delete[] buffer; // free the old buffer
buffer = newArray; // point it to the newly allocated memory
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.