[英]How to “change the size” of an array [Pointers being used]
因此,我必须使用内置在类中的数组来实现堆栈,并且如果“堆栈”已满,则应该增加尝试但失败的数组的大小。 所以我只是好奇我需要做些什么才能使它起作用。
class AbstractStack
{
private:
Type elements; // elements in the array
Type max;
Type *s;
public:
AbstractStack(Type num) { //CONSTRUCTOR
elements= -1;
this->max = num;
s = new Type[max];
}
/* bunch of code that does not apply to this issue
*/
void push ( Type e ) {
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
Type *temp = new Type[max + (max/2)];
for (int i = 0; i < elements+1; i++) {
temp[i] = s[i];
}
s = temp;
delete temp;
elements++;
s[elements] ;
return;
}
else {
elements++;
s[elements] = e;
}
}
当我使用这个new的大小时,我得到的正确大小比以前大1,因为仅在尝试向整个堆栈中添加1个元素时才调用此函数,但是当我尝试使用top函数时,它只会给出我0然后我得到类似50行错误代码的开始:
*** Error in `./a.out': double free or corruption (top): 0x0000000000c53cf0 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7c619)[0x7fa34a270619]
./a.out[0x400c38]
./a.out[0x400b48]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7fa34a215c05]
./a.out[0x400979]
Type elements; // elements in the array
Type max;
这些都是int
或unsigned
或size_t
,或您希望进行计数的任何值。 它们与Type
无关。
void push ( Type e ) {
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
Type *temp = new Type[max + (max/2)];
之后,您应该将max
增加到max*3/2
。
for (int i = 0; i < elements+1; i++) {
循环条件应为i < elements
。 您正在使用元素零,并且element[elements]
还不存在。
temp[i] = s[i];
}
s = temp;
delete temp;
最后两行应为delete[] s
后跟s = temp
。
elements++;
s[elements] ;
最后两行应为s[elements++] = e
;
return;
return
在这里是多余的。
}
else {
elements++;
s[elements] = e;
同样,最后两行应为s[elements++] = e
;
}
}
更正和简化的版本:
int elements;
int max;
// ...
void push ( Type e ) {
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
max += max/2;
Type *temp = new Type[max];
for (int i = 0; i < elements; i++) {
temp[i] = s[i];
}
delete[] s;
s = temp;
}
s[elements++] = e;
}
你必须删除旧的阵列( s
,而不是新的() temp
):
delete[] s;
s = temp;
另外:请确保您的类具有适当的析构函数(删除s
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.