2012-02-12 85 views
1

我有一个动态分配的数组:如何从动态分配的数组中删除元素?

myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel]; 

我想通过这个阵列中的所有元素循环和消除这些能够满足我的条件(例如过大的矩形)。

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

只是为了记录:我不能使用STL容器。

+3

我想你在你最后一句话中意外地用了一个词。 – 2012-02-12 03:26:20

+0

只是可能有一个缺失 – 2012-02-12 03:27:42

+1

如果你正在做这个转移很多,你会更好的与std :: vector – 2012-02-12 03:29:36

回答

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. 
1

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

+0

这听起来不错。你能提供一些代码示例吗? – Patryk 2012-02-12 03:33:17

1

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

这样你就不需要到转移想要的元素融入到新阵列,但只是删除不需要的元素。

有关您的用例的更多信息将帮助我们考虑更好的替代方案。

0

,如果你有数据的阵列数量较大,这将是对使用循环

也许你应该建立自己的阵列管理类(查找,添加,deleteAt等)转移的问题。

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