Reputation: 35
We have the Enqueue and Dequeue methods to work on a queue in C#. But is there a way we can remove the last item in the queue? Dequeue actually removes the item from the top.
Upvotes: -1
Views: 5201
Reputation: 11
This is an expensive operation, so I only do this rarely. People here getting mad and not answering... all you do is just use a second Queue to move everything to:
// original queue must already be filled up
Queue<Waypoint> waypoints = new Queue<Waypoint>();
// fill it up...
Queue<Waypoint> temp = new Queue<Waypoint>();
while (waypoints.Count > 0) // stop one short of the end
{
temp.Enqueue(waypoints.Dequeue());
}
Waypoint wp = waypoints.Dequeue();
// get the last one and do what you desire to it...
// I modified mine and then added it back, this is not needed
temp.Enqueue(new Waypoint(wp.pos, (p.vectorPath[0] - wp.pos).normalized));
// necessary: you have waypoints empty now so you have to swap it for temp:
waypoints = temp;
Upvotes: 1
Reputation: 31
Like Patrick stated the queue is meant to be first in first out. Think of it like a printer queue, the first page that goes to into the printer queue is the first to be printed out.
Look into using a List instead of an Array, I found lists a bit easier to manipulate with a bunch of extended methods that arrays do not have. http://www.dotnetperls.com/list
Here is a link to how to remove the last item in a list which has a few different ways of accomplishing it.
How to remove the last element added into the List?
hope this helps!
Upvotes: -1
Reputation: 192
Maybe you should consider using a Stack instead of a Queue.
Stack works similar to a queue but instead of the first in first out behaviour a stack is used when you need a last in first out solution for your objects
Upvotes: 0
Reputation: 157136
The entire purpose of a Queue
is to walk the collection from top to bottom. If you want a collection type that allows removing from the back too (or any place in the collection), use another collection type, a List<T>
for example.
Upvotes: 1