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.
这篇关于是否堆栈<>构造函数在从另一个初始化时反转堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否堆栈<>构造函数在从另一个初始化时反转堆栈?
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
