将旧指针数组的元素复制到新的指针数组中?

时间:2012-09-16 01:22:22

标签: c++ arrays copy element delete-operator

我需要一些C ++项目的帮助。我要做的是从指针数组中删除给定的元素。向我讲述的技术是创建一个包含少量元素的新数组,并将旧数组中的所有内容复制到除指定元素之外的新数组中。之后,我必须将旧阵列指向新阵列。

以下是我已经拥有的一些代码:

我正在使用自定义结构......

Data **values = null;    // values is initialized in my insert function so it is
                         //   populated
int count;               // this keeps track of values' length



bool remove(Data * x) {
    Data **newArray = new Data *[count - 1];

    for (int i = 0; i < count; i++) {
        while (x != values[i]) {
            newArray[i] = values[i];
        }
        count -= 1;
        return true;
    }
    values = newArray;

    return false;
}

到目前为止,insert函数工作并输出填充的数组,但是当我运行remove all时它会使数组变小,但不会删除所需的元素。我每次都使用第0个元素作为控件。

这是我得到的输出:

count=3 values=[5,6,7]            // initial insertion of 5, 6, 7
five is a member of collection? 0
count=3 values=[5,6]              // removal of 0th element aka 5, but doesn't work
five is a member of collection? 0
count=4 values=[5,6,5]            // re-insertion of 0th element (which is stored in
five is a member of collection? 0 // my v0 variable)

有没有人能够朝着正确的方向推动我完成这项工作?

2 个答案:

答案 0 :(得分:2)

首先,你的代码泄漏内存就好了!接下来,您只复制第一个元素,如果第一个元素恰好是您要删除的元素,则不会。此外,当您从函数返回时,您根本没有更改内部状态。你肯定想要按照

的方式做点什么
Data** it = std::find(values, values + count, x);
if (it != values + count) {
     std::copy(it + 1, values + count, it);
     --count;
     return true;
}
return false;

那就是说,如果有人教你实施像std::vector<T>那样涉及每次操作的重新分配的东西,那么现在是改变学校的时候了!内存分配相对昂贵,你想避免它们。也就是说,当实现像std::vector<T>这样的东西时,你确实想要像std::vector<T>那样实现它!那就是你保留一个可能比有更多元素的内部缓冲区,并记住你正在使用多少元素。插入新元素时,如果当前数组中没有空格,则只分配一个新数组(即使总是在末尾添加元素,这样做也很容易导致二次复杂度)。删除元素时,只需向上移动所有尾随对象,并记住数组中只有一个对象。

答案 1 :(得分:0)

试试这个:

bool remove(Data * x)
{
    bool found = false;

    // See if x is in the array.
    for (int i = 0; i < count; i++) {
        if (x != values[i]) {
            found = true;
            break;
        }
    }

    if (!found)
    {
        return false;
    }

    // Only need to create the array if the item to be removed is present
    Data **newArray = new Data *[count - 1];

    // Copy the content to the new array
    int newIndex = 0;
    for (int i = 0; i < count; i++)
    {
        if (x != values[i])
            newArray[newIndex++] = values[i];
    }

    // Now change the pointers.
    delete[] values;
    count--;
    values = newArray;
    return true;
}

请注意,有一个潜在的假设,即如果数组中存在x那么它只有一次!该代码不适用于多次出现,留给您,看看这是如何进行学校练习。