Does Stacklt;gt; constructor reverse the stack when being initialized from other one?(是否堆栈lt;gt;构造函数在从另一个初始化时反转堆栈?)
问题描述
代码如下:
var s = new Stack<int>();
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
var ns = new Stack<int>(s);
var nss = new Stack<int>(new Stack<int>(s));
然后我们看看结果
tbLog.Text += "s stack:";
while(s.Count > 0)
{
tbLog.Text += s.Pop() + ",";
}
tbLog.Text += Environment.NewLine;
tbLog.Text += "ns stack:";
while (ns.Count > 0)
{
tbLog.Text += ns.Pop() + ",";
}
tbLog.Text += Environment.NewLine;
tbLog.Text += "nss stack:";
while (nss.Count > 0)
{
tbLog.Text += nss.Pop() + ",";
}
产生以下输出:
s stack:4,3,2,1,
ns stack:1,2,3,4,
nss stack:4,3,2,1,
所以,ns
栈被还原为 s
栈并且 nss
栈与 s
栈相同.
So, ns
stack is reverted s
stack and nss
stack is the same as s
stack.
推荐答案
采用 IEnumerable<T>
的堆栈构造函数将项目推入就好像调用了 Add
多次.
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.
这篇关于是否堆栈<>构造函数在从另一个初始化时反转堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否堆栈<>构造函数在从另一个初始化时反转堆栈?


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01