Does Stack<> constructor reverse the stack when being initialized from other one?

帅比萌擦擦* 提交于 2019-12-04 06:47:39

The stack constructor which takes an IEnumerable<T> pushes the items on as if Add were called multiple times.

Iterating over a stack iterates in "pop" order... so when you construct one stack from another, it will add the top of the original stack first, then put the "second from the top" element on top of that in the new stack, etc... effectively reversing it.

The constructor you are using for ns an nss is Stack<T>(IEnumerable<T>). When you enumerate a stack it enumerates from top to bottom. But when creating a stack it pushes the elements in enumerated order. So the last enumerated item (last in the source) will be top of the new stack.

So yes, it does reverse the order of elements.

The clue to your surprise is in your question:

Does Stack<> constructor reverse the stack when being initialized from other one ?

The ctor you are referring to does not accept another Stack - rather, it accepts an IEnumerable. That is, there is no special treatment for constructing a Stack from a Stack, as compared to constructing a Stack from any other IEnumerable.

So when you do try and construct a Stack from a Stack, the source Stack is consumed in its natural enumeration order, ie in the popping order. And the new Stack is constructed by pushing the items of the incoming IEnumerable. Hence the behaviour you are seeing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!