您将如何获得队列中的第一个和最后一个项目? [英] How would you obtain the first and last items in a Queue?

查看:26
本文介绍了您将如何获得队列中的第一个和最后一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个滚动值集合,我在其中指定集合的​​大小,并且任何时候添加新值,超过此指定大小的任何旧值都会被丢弃.显然(并且我已经对此进行了测试)用于此行为的最佳集合类型是队列:

Say I have a rolling collection of values where I specify the size of the collection and any time a new value is added, any old values beyond this specified size are dropped off. Obviously (and I've tested this) the best type of collection to use for this behavior is a Queue:

myQueue.Enqueue(newValue)
If myQueue.Count > specifiedSize Then myQueue.Dequeue()

但是,如果我想计算队列中第一项和最后一项之间的差异,该怎么办?显然我无法通过索引访问这些项目.但是从 Queue 切换到实现 IList 的东西似乎有点矫枉过正,编写一个新的类似 Queue 的类也是如此.现在我有:

However, what if I want to calculate the difference between the first and last items in the Queue? Obviously I can't access the items by index. But to switch from a Queue to something implementing IList seems like overkill, as does writing a new Queue-like class. Right now I've got:

Dim firstValue As Integer = myQueue.Peek()
Dim lastValue As Integer = myQueue.ToArray()(myQueue.Count - 1)
Dim diff As Integer = lastValue - firstValue

ToArray() 的调用让我感到困扰,但我并没有找到更好的选择.有什么建议吗?

That call to ToArray() bothers me, but a superior alternative isn't coming to me. Any suggestions?

推荐答案

你可以做的一件事是有一个临时变量来存储刚刚入队的值,因为那将是最后一个值,因此可以访问该变量得到那个值.

One thing you could do is have a temporary variable that stores the value that was just enqueued because that will be the last value and so the variable can be accessed to get that value.

这篇关于您将如何获得队列中的第一个和最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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