选择队列中的特定对象(即 peek +1)
如果 Peek 返回队列中的下一个对象,是否有一种方法可以用来获取特定对象?例如,我想找到队列中的第三个对象并更改其值之一?
现在我只是通过队列进行 foreach 这可能是最好的解决方案,但我不知道是否有一些特殊的东西可以与 peek 一起使用?即 Queue.Peek(2)
if Peek returns the next object in a queue, is there a method I can use to get a specific object? For example, I want to find the third object in the queue and change one of its values?
right now Im just doing a foreach through the queue which might be the best solution, but I didnt know if there was something special you can use with peek? ie Queue.Peek(2)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想直接访问元素(使用
O(1)
操作),请使用数组而不是队列,因为队列具有不同的功能 (FIFO)。队列上的随机访问操作将是
O(n)
,因为它需要迭代集合中的每个元素......这反过来又使其成为顺序访问,而不是比直接随机访问。再说一遍,由于您使用的是 C#,因此可以使用 System.Linq 中的queue.ElementAt(n)(因为
Queue
实现了>IEnumerable
),但这不会是O(1)
即它仍然会迭代元素。If you want to access elements directly (with an
O(1)
operation), use an array instead of a queue because a queue has a different function (FIFO).A random access operation on a queue will be
O(n)
because it needs to iterate over every element in the collection...which in turn makes it sequential access, rather than direct random access.Then again, since you're using C#, you can use
queue.ElementAt(n)
fromSystem.Linq
(sinceQueue
implementsIEnumerable
) but that won't beO(1)
i.e. it will still iterate over the elements.虽然这仍然是 O(n),但如果您使用 LINQ 扩展方法
ElementAt()
或ElementAtOrDefault()
,那么它肯定更容易阅读,这些是的扩展IEnumerable
,Queue
实现。编辑
如果您确实遵循将队列转换为数组的其他建议,只是为了此操作,您需要确定队列的可能大小以及您要从队列开头查找的索引的距离是否合理调用 .ToArray() 的 O(n) 操作。 ElementAt(m),更不用说为其创建辅助存储位置的空间要求了。
Although this is still O(n), it's certainly easier to read if you use the LINQ extention methods
ElementAt()
orElementAtOrDefault()
, these are extentions ofIEnumerable<T>
, whichQueue<T>
implements.Edit
If you do go with the other suggestions of converting your Queue to an array just for this operation that you need to decide if the likely sizes of your queue and the distance of the index you'll be looking for from the start of your queue justify the O(n) operation of calling .ToArray(). ElementAt(m), not to mention the space requirements of creating a secondary storage location for it.
foreach 通过队列。有点悖论。
但是,如果您可以 foreach,则它是一个 IEnumerable,因此通常的 linq 扩展适用:
或
foreach through a queue. Kind of a paradox.
However, if you can foreach, it is an IEnumerable, so the usual linq extensions apply:
or
您可以一次性执行类似的操作:
但是,我不建议大量使用它,因为它将整个队列复制到一个数组,从而无论如何都会迭代整个队列。
You could do something like this as a one off:
I wouldn't recommend using it a lot, however, as it copies the whole queue to an array, thereby iterating over the whole queue anyway.