0

我正在尝试将一个 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;
}
4

2 回答 2

3

您的insert功能永远不会更新Num。尝试Pool[Num++] = X;或类似的东西。

于 2012-10-31T21:53:45.167 回答
0

You probably want to increment the number of element but only after copying the new element in: the first element should have index 0. Basically, your insert() function should look something like this:

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;
}

Of course, this assumes that Pool is reasonably declared as std::unique_ptr<int[]> (or something with similar functionality which is easy to write if necessary). The reason to use std::unique_ptr<int[]> rather than raw pointers is that they automatically clean up resources when they are destroyed. Copying a sequence of ints won't throw an exception but if int get's replaced by a std::string or a template parameters there is potential to throw exceptions.

于 2012-10-31T21:56:45.520 回答