对数组执行浅复制以调整数组大小有何影响?
如果我对深复制和浅复制的理解是正确的,那么我的问题是不可能的。 如果您有一个数组 (a[10]) 并执行浅复制 (b[20]),这不是不可能的吗,因为 b 中的数据不连续?
如果我完全错了,有人可以建议一种快速的方法来模仿(在 C# 中)C++ 进行重新分配以调整数组大小的能力。
注意
我正在查看 System.Array 对象的 .Clone() 和 .Copy() 成员。
If my understanding of deep and shallow copying is correct my question is an impossible one.
If you have an array (a[10]) and perform a shallow copy (b[20]) wouldn't this be impossible as the data in b wouldn't be contiguous?
If i've got this completely wrong could someone advise a fast way to immitate (in c#) c++'s ability to do a realloc in order to resize an array.
NOTE
Im looking at the .Clone() and .Copy() members of the System.Array object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法调整现有数组的大小,但是可以使用:
这会分配一个新数组,将旧数组中的数据复制到新数组中,并更新
arr
变量(由-ref 在这种情况下)。 你是这个意思吗?但是,仍然指向旧数组的任何其他引用将不会更新。 更好的选择可能是使用
List
- 这样您就不需要手动调整它的大小,并且不会遇到过时引用的问题。 您只需添加
/删除
等。通常,您不会经常直接使用数组。 它们有它们的用途,但它们不是默认情况。回复您的评论;
List
不装箱。 这是关于泛型的要点之一; 在底层,List
是T[]
的包装器,因此List
有一个int[ ]
- 没有拳击。 旧的ArrayList
是object[]
的包装器,因此确实盒子; 当然,拳击如果我记得的话,它会找到实际的细节被内部调用隐藏- 但本质上在分配一个新数组之后,它是两个数组之间数据的 blit (memcpy),所以它应该很快; 请注意,对于引用类型,这仅复制引用,而不复制堆上的对象。 但是,如果您定期调整大小,T
的大小,然后使用Buffer.BlockCopy
来blit内容List
通常会简单得多(并且更快,除非您基本上重新实现List
重新实现备用容量的功能以尽量减少调整大小的次数)。You can't resize an existing array, however, you can use:
This allocates a new array, copies the data from the old array into the new array, and updates the
arr
variable (which is passed by-ref in this case). Is that what you mean?However, any other references still pointing at the old array will not be updated. A better option might be to work with
List<T>
- then you don't need to resize it manually, and you don't have the issue of out-of-date references. You justAdd
/Remove
etc. Generally, you don't tend to use arrays directly very often. They have their uses, but they aren't the default case.Re your comments;
List<T>
doesn't box. That is one of the points about generics; under the hood,List<T>
is a wrapper aroundT[]
, so aList<int>
has anint[]
- no boxing. The olderArrayList
is a wrapper aroundobject[]
, so that does box; of course, boxing isn't as bad as you might assume anyway.Array.Resize
;if I recall, it finds the size ofthe actual details are hidden by an internal call - but essentially after allocating a new array it is a blit (memcpy) of the data between the two arrays, so it should be pretty quick; note that for reference-types this only copies the reference, not the object on the heap. However, if you are resizing regularly,T
, then usesBuffer.BlockCopy
to blit the contentsList<T>
would usually be a lot simpler (and quicker unless you basically re-implement whatList<T>
does re spare capacity to minimise the number of resizes).