我可以限制通用堆栈的深度吗? [英] Can I Limit the depth of a Generic Stack?

查看:54
本文介绍了我可以限制通用堆栈的深度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置的方法来限制System.Collection.Generics.Stack的深度?这样一来,如果您已达到最大容量,则推入一个新元素会移除堆栈的底部吗?

Is there a built in way to limit the depth of a System.Collection.Generics.Stack? So that if you are at max capacity, pushing a new element would remove the bottom of the stack?

我知道我可以通过转换为数组并重建堆栈来做到这一点,但我认为上面可能已经有一个方法.

I know I can do it by converting to an array and rebuilding the stack, but I figured there's probably a method on it already.

我写了一个扩展方法:

    public static void Trim<T> (this Stack<T> stack, int trimCount) 
    {
        if (stack.Count <= trimCount)
            return;

       stack = new 
            Stack<T>
            (
                stack
                    .ToArray()
                    .Take(trimCount)
            );           
    }

因此,它在修剪后会返回一个新的堆栈,但不是功能性的不变性=)

So, it returns a new stack upon trimming, but isn't immutability the functional way =)

这样做的原因是我将应用程序的撤消步骤存储在堆栈中,而我只想存储有限数量的步骤.

The reason for this is that I'm storing undo steps for an app in a stack, and I only want to store a finite amount of steps.

推荐答案

您要查找的内容称为辍学堆栈. AFAIK,BCL不包含一个,尽管实现起来很简单.通常,撤消"和重做"功能依赖于此类数据结构.

What you are looking for is called a dropout stack. AFAIK, the BCL does not contain one, although they are trivial to implement. Typically Undo and Redo functionality relies on such data structures.

它们基本上是一个数组,当您将其推入堆栈时,堆栈的顶部"会在数组周围移动.最终,当堆栈已满时,顶部将返回到开头,并替换堆栈的底部".

They are basically an array, and when you push onto the stack the 'top' of the stack moves around the array. Eventually the top will wrap back to the beginning when the stack is full and replace the 'bottom' of the stack.

Google并没有提供太多信息.这是我能找到的最好的东西:

Google didn't provide much info on it. This is the best i could find:

(警告PDF) http://courses.cs.vt.edu/~cs2704/spring04 /projects/DropOutStack.pdf

这里有一些样板代码,可以帮助您入门.我让您填写其余内容(健全性检查,计数,索引器等)

Here's some boiler plate code, to get you started. I'll let you fill in the rest (sanity checking, count, indexer, etc.)

class DropOutStack<T>
{
    private T[] items;
    private int top = 0;
    public DropOutStack(int capacity)
    { 
        items = new T[capacity];
    }

    public void Push(T item)
    {
        items[top] = item;
        top = (top + 1) % items.Length;
    }
    public T Pop()
    {
        top = (items.Length + top - 1) % items.Length;
        return items[top];
    }
}

这篇关于我可以限制通用堆栈的深度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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