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()
但是,如果我想计算队列中第一项和最后一项之间的差异,该怎么办?显然我无法通过索引访问这些项目.但是从 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.
这篇关于您将如何获得队列中的第一个和最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您将如何获得队列中的第一个和最后一个项目?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30