【发布时间】:2014-01-29 23:22:14
【问题描述】:
我正在尝试编写一个将项目推送到动态分配数组末尾的函数(不允许使用向量)。如果列表太小而无法存储下一个数字,一旦它进入该区域以使列表的大小增加一倍,这一切都变得糟糕透顶,并开始从计算机向我反馈随机数。谁能明白为什么它没有像预期的那样翻倍?
int *contents_;
int *temp;
int size_ = 0;
int capacity_ = 1;
void pushBack(int item) /**appends the specified value to DynArray; if the contents array is full,
double the size of the contents array and then append the value **/
{
if (size_ == capacity_)
{
capacity_ = (2*capacity_);
temp = new int[capacity_];
for (int i = 0; i < size_; ++i)
{
temp[i] = contents_[i];
}
delete [] contents_;
contents_ = temp;
}
contents_[size_++] = item;
}
编辑 ** 我忘了说。这是一个类外的功能。这是在标题和主要:
main()
{
DynArray myArray;
myArray.pushBack(2);
myArray.pushBack(3);
myArray.printArray();
return 0;
}
【问题讨论】:
-
如何初始化和使用这个?
-
如果这是家庭作业,我认为数组不算作列表。
标签: c++ arrays memory dynamic push