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.
这篇关于是否堆栈<>构造函数在从另一个初始化时反转堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否堆栈<>构造函数在从另一个初始化时反转堆栈?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01