是否堆栈<>构造函数在从另一个初始化时反转堆栈?

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.

这篇关于是否堆栈&lt;&gt;构造函数在从另一个初始化时反转堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Can I initialize a BCL immutable collection using braces?(我可以使用大括号初始化BCL不可变集合吗?)
The type initializer for #39;System.Data.Entity.Internal.AppConfig#39; threw an exception on a Sub Website(“System.Data.Entity.Internal.AppConfig的类型初始化程序在子网站上引发异常)
Possible to initialize multiple variables from a tuple?(可以从一个元组初始化多个变量吗?)
error loading database initializer with EF6(使用 EF6 加载数据库初始化程序时出错)
How to force fire OnModelCreating every DataContext initialized up(如何强制触发 OnModelCreating 每个初始化的 DataContext)
The type appear in two structurally incompatible initializations within a single LINQ to Entities query(该类型出现在单个 LINQ to Entities 查询中的两个结构不兼容的初始化中)