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

C++ 如何从动态分配的数组中删除元素?,c++,arrays,dynamic-arrays,C++,Arrays,Dynamic Arrays,我有一个动态分配的数组: myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel]; 我想循环此数组中的所有元素,并删除符合我条件的元素(例如,太大的矩形) 我一直在想,我可以循环这个数组,得到满足条件的元素数,然后分配一个新数组。但是我如何才能将这些“想要的”元素“转移”到我的新数组中呢 仅供记录:我不能使用STL容器。只需将下一个数组位置移到需要删除的位置上,然后将所有内容移到数组末尾。我同意-使用std::vector

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

myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];
我想循环此数组中的所有元素,并删除符合我条件的元素(例如,太大的矩形)

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


仅供记录:我不能使用STL容器。

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

我同意-使用std::vector。这样可以避免许多其他潜在问题。如果您真的想使用动态数组,请参见以下问题:

您的问题看起来非常适合使用链表。但是,您必须去掉
新的myRectangle[lastMaxLabel]
部分,因为您必须将其作为
Insert()
函数的pert来实现

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


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

如果您的数组中有大量数据,那么转换使用循环将是一个问题

也许您应该构建自己的阵列管理类(查找、添加、删除等)


我的建议是使用链接列表节点方法。。它将比你使用循环换档更快

我想你无意中在最后一句话中出现了一个单词。可能会有一个遗漏。如果你做了大量的移位,你最好使用std::Vector。你是在问如何删除一个,还是将找到的元素插入另一个数组?@Dan我真的不在乎。这两种方法都适合我,听起来不错。你能提供一些代码样本吗?谢谢Joe,但我不能使用任何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.