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

时间:2012-02-12 03:25:00

标签: c++ arrays dynamic-arrays

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

myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];

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

我一直在想我可以遍历这个数组并获得满足条件的元素数量,然后分配一个新数组。但我怎样才能转移'这些'想要'元素进入我的新阵列?

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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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.

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

我同意Michael Chinen - 请改用std :: vector。你会以这种方式避免许多其他潜在的问题。如果您确实想使用动态数组,请参阅此问题:Remove an array element and shift the remaining ones

答案 4 :(得分:0)

如果您在数组中有大量数据,那么使用循环

进行转换就会出现问题

也许你应该建立自己的数组管理类(find,add,deleteAt等)。

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