你将如何获得一个队列的第一个和最后一个项目? [英] How would you obtain the first and last items in a Queue?
问题描述
说我有我的指定的集合和一个新值添加任何时候的大小值的滚动集合,超出了规定大小的任何旧值将被丢弃掉。显然,(我测试过这一点)收集的最佳类型用于此行为是队列:
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()
不过,如果我要计算在队列中的第一项和最后一项之间的区别是什么?很显然,我不能按索引访问的项目。但是,从队列中切换到的东西贯彻IList中似乎有点小题大做,因为它写一个新的队列状类。现在我已经得到了:
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屋!