C# 容器中的push_back操作
我需要像 C++ 矢量这样的容器。通常建议使用List,但它不支持push_back操作。我知道实现 List 容器的扩展方法相当简单。但。 Stack 会是一个不错的选择吗?
谢谢!
I need container like c++ vector. Often it is adviced to use List, but it dosen't support push_back operation. I know this is rather simple implementing an extension method for List container. But. Would Stack be a good alternative?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它确实支持
List。添加
。这不是您要找的吗?It does support
List<T>.Add
. Isn't that what you are looking for?您不会获得与 C# 中的
vector
直接等效的对象,因为您无法控制内存的分配方式。std::vector
将始终将其内存存储在连续的块中;因此,如果需要,您可以像这样访问它:C# 无法控制内存的分配方式,因此向量/数组和列表之间不存在区别。您可以使用您想要的
List
容器。You won't get a direct equivalent to
vector
in C# because you have no control over how the memory is allocated.std::vector
will always have its memory in a contiguous block; so if needed, you could access it like so:C# gives you no control over how the memory is allocated, so the distinction between a vector/array and a list is non-existent. You can use the
List
container is what you want.ListName.Add(element);
的复杂度为O(1)
ListName.Insert(index,element);
的复杂度为O(n )
复杂性,第一个就像我们在 cpp 中使用的
push_back()
函数,它会附加元素insert 主要用于当我们想要在它涉及的特定索引处添加元素时元素的移动,因此根据您放置元素的位置,元素的复杂性可能会略有不同,因为在大列表的开头添加元素必须移动元素的其余部分,而当我们在列表末尾输入元素时,它花费的时间会稍微少一些。
ListName.Add(element);
hasO(1)
complexityListName.Insert(index,element);
hasO(n)
complexityas the first one is like the
push_back()
function we use in cpp and it will append the elementinsert is used mainly when we want to add element at a specific index it involves shifting of element so depending where you put your element complexity may slightly vary as adding element at beginning of large list has to shift rest of the element where as we enter element at the ending of the list it take slightly less time.