Selecting specific object in queue ( ie peek +1)

Leroy Jenkins picture Leroy Jenkins · May 26, 2011 · Viewed 32.3k times · Source

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)

Answer

Andreas Grech picture Andreas Grech · May 26, 2011

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) from System.Linq (since Queue implements IEnumerable) but that won't be O(1) i.e. it will still iterate over the elements.