是否堆栈<>构造函数在从另一个初始化时反转堆栈? [英] Does Stack<> constructor reverse the stack when being initialized from other one?

查看:27
本文介绍了是否堆栈<>构造函数在从另一个初始化时反转堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

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;构造函数在从另一个初始化时反转堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆