如何从动态分配的数组中删除元素

How to remove elements from dynamically allocated array?

本文关键字:删除 元素 数组 动态分配      更新时间:2023-10-16

我有一个动态分配的数组:

myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];

我想循环遍历这个数组中的所有元素,并删除符合我条件的元素(例如,太大的矩形)。

我一直在想,我可以循环遍历这个数组,得到满足我的条件的元素数量,然后分配一个新数组。但是,我如何将这些"想要的"元素"转移"到我的新数组中呢?

记录在案:我不能使用STL容器。

myRectangle * lastRectanglesArray = new myRectangle[lastMaxLabel];
// initialize the entries in the lastRectanglesArray
// create a temporary array which contains info about each individual
// entry. namely, it only holds info about whether the entry should
// be kept, or deleted.
// we also use the 'entries' value, which is the number of entries
// in the new array
bool * entriesToKeep = new bool[lastMaxLabel];
int entries = 0;
// check each entry, and mark whether it should be kept or deleted
for (int i = 0; i != lastMaxLabel; ++i) {
    // check whether the entry should be kept or deleted...
    // here, i just put a function with signature like:
    // bool shouldKeepRectangle(const myRectangle &);
    entriesToKeep[i] = shouldKeepRectangle(lastRectanglesArray[i]);
    if (entriesToKeep[i]) ++entries;
}
// create a new array that will contain the entries that should be kept
myRectangle * rectanglesArray = new myRectangle[entries];
// assign the entries in the new array
for (int i = 0, j = 0; i != lastMaxLabel && j != entries; ++i) {
    if (entriesToKeep[i])
        rectanglesArray[j++] = lastRectanglesArray[i];
}
// free the memory held by the temp array
delete [] entriesToKeep;
// if the old array is not needed anymore, delete it
delete [] lastRectanglesArray;
// and here you have rectanglesArray, a brand new array that contains
// only the elements that you need.

只需将下一个数组位置移到需要删除的位置上,然后将所有内容移到数组的末尾。

您的案例看起来是使用链表的完美案例。但是,您必须取消new myRectangle[lastMaxLabel]部分,因为您必须将其作为Insert()函数的一部分来实现。

这样,您就不需要将所需的元素转移到新的数组中,而只需删除不需要的元素。

更多地了解您的用例将有助于我们思考更好的替代方案。

我同意Michael Chinen的观点——使用std::vector。这样可以避免许多其他潜在的问题。如果您真的想使用动态数组,请参阅以下问题:删除一个数组元素并将剩余的元素移位

如果数组中有大量数据,那么使用循环进行移位将是一个问题

也许您应该构建自己的数组管理类(find、add、deleteAt等)。

我的建议使用链表节点方法。。它会更快,而不是你使用循环移位。