如何从动态分配的数组中删除元素?
我有一个动态分配的数组:
myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];
我想循环遍历该数组中的所有元素并删除那些满足我的条件的元素(例如太大的矩形)。
我一直在想我可以循环遍历这个数组并获取满足我的条件的元素数量,然后分配一个新数组。但是我怎样才能将这些“想要的”元素“转移”到我的新数组中呢?
仅供记录:我不能使用 STL 容器。
I have a dynamically allocated array :
myRectangle lastRectanglesArray = new myRectangle[lastMaxLabel];
I would like to loop through all elements in this array and remove these that will meet my condition (e.g. too big rectangle).
I have been thinking that I can loop through this array and get the number of elements that would satisfy my condition and then allocate a new array. But how can I 'transfer' these 'wanted' elements into my new array ?
Just for the record: I cannot use STL containers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需将下一个数组位置移到需要删除的位置上,然后将所有内容移至数组末尾即可。
Just move the next array location over the one that needs to be deleted, and shift everything over til the end of the array.
您的看起来是使用链接列表的完美案例。但是,您必须取消
new myRectangle[lastMaxLabel]
部分,因为您必须将其实现为Insert()
函数的一部分。这样,您就不需要将想要的元素转移到新数组中,而只需删除不需要的元素。
对您的用例的任何更多了解都将帮助我们想到更好的替代方案。
Yours look like the perfect case for using a Linked List. You would however have to do away with the
new myRectangle[lastMaxLabel]
part as you would have to implement it as pert of yourInsert()
function.This way you would not require to transfer the wanted elements into a new array, but just delete the unwanted element.
Any more light on your use-case would help us to think of better alternatives.
我同意 Michael Chinen - 使用 std::vector 代替。通过这种方式,您将避免许多其他潜在的问题。如果您确实想使用动态数组,请参阅此问题:删除一个数组元素并移动其余元素
I agree with Michael Chinen - use std::vector instead. You'll avoid lots of other potential problems this way. If you really want to use dynamic arrays, see this question: Remove an array element and shift the remaining ones
如果数组中有大量数据,这将成为使用循环转移的问题
,也许您应该构建自己的数组管理类(find、add、deleteAt等)。
我的建议使用链接列表节点方法..它会比使用循环进行移位更快。
if you have a big amount of data in array that will be a problem for shifting using loop
maybe you should build your own array management class (find,add,deleteAt,etc).
my suggestion use link list node method.. it will be faster rather then you use loop for shifting.