為了學習資料結構,我為堆疊制作了這個類。它適用于整數,但它會引發一個神秘的字串錯誤。類 List 是我的堆疊的 API。它的意思是在達到限制時自動調整大小。整個代碼只是為了學習,但我得到的錯誤沒有任何意義,它發生在某些匯編代碼的某個地方。
#include <iostream>
#include<string>
using namespace std;
class List {
private:
int N = 0;
string* list = new string[1];
void resize(int sz) {
max = sz;
string* oldlist = list;
string* list = new string[max];
for (int i = 0; i < N; i ) {
list[i] = oldlist[i];
}
}
int max = 1;
public:
void push(string str) {
if (N == max) {
resize(2 * N);
}
cout << max << endl;
list[N] = str;
N ;
}
void pop() {
cout << list[--N] << endl;
}
};
int main()
{
string in;
List list;
while (true) {
cin >> in;
if (in == "-") {
list.pop();
}
else {
list.push(in);
}
}
}
uj5u.com熱心網友回復:
string* list = new string[max];在resize方法中定義了一個名為list“ shadows ”的新變數,替換了成員變數list。成員list不變,區域變數list在函式結束時超出范圍,丟失所有作業。
修復:更改
string* list = new string[max];
到
list = new string[max];
這樣該函式將使用成員變數。
完成后不要忘記delete[] oldlist;釋放它指向的存盤空間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430744.html
