c++中的数组动态内存分配

dynamic memory allocation with arrays in c++

本文关键字:内存 分配 动态 数组 c++      更新时间:2023-10-16

我正试图将int插入类对象中的数组中,但我不知道我做错了什么。我的代码的当前状态从未将int插入数组中。

基本上,我想做的是,当我调用insert(int)时,它会检查数组中是否还有空间,如果有,它会添加它,否则它会在数组中重新分配8个空间。

这是一些相关的班级信息

private:
unsigned Cap;    // Current capacity of the set
unsigned Num;    // Current count of items in the set
int * Pool;      // Pointer to array holding the items
public:
// Return information about the set
//
bool is_empty() const { return Num == 0; }
unsigned size() const { return Num; }
unsigned capacity() const { return Cap; }
// Initialize the set to empty
//
Set()
{
Cap = Num = 0;
Pool = NULL;
}

这是我正在上工作的代码

bool Set::insert(int X)
{
bool Flag = false;
if (Num == Cap)
{
//reallocate
const unsigned Inc = 8;
int * Temp = new int[Cap+Inc];
for (unsigned J=0;J<Num;J++)
{
Temp[J] = Pool[J];
}
delete [] Pool;
Pool = Temp;
Cap = Cap+Inc;
}
if(Num < Cap)
{
Pool[Num+1] = X;
Flag = true;
}
return Flag;
}

insert函数从不更新Num。试试Pool[Num++] = X;或类似的东西。

您可能想增加元素的数量,但只能在复制新元素后才增加:第一个元素的索引应该为0。基本上,你的insert()函数应该是这样的:

bool Set::insert(int X)
{
if (Num == Cap)
{
const unsigned Inc(std::max(8, 2 * Cap));
std::unique_ptr<int[]> Temp(new int[Cap+Inc]);
std::copy(Pool.get(), Pool.get() + Num, Temp.get());
Pool.swap(Temp);
Cap += Inc;
}
Pool[Num] = X;
++Num;
return true;
}

当然,这是假设Pool被合理地声明为std::unique_ptr<int[]>(或者具有类似功能的东西,如果必要的话很容易编写)。使用std::unique_ptr<int[]>而不是原始指针的原因是,当资源被销毁时,它们会自动清理资源。复制int的序列不会引发异常,但如果intstd::string或模板参数替换,则有可能引发异常。