繁体   English   中英

在C ++中使用数组动态分配内存

[英]dynamic memory allocation with arrays in c++

我试图将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序列不会引发异常,但是如果将int get替换为std::string或模板参数,则有可能引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM