[英]Removing the last item from a queue in C#
我们有 Enqueue 和 Dequeue 方法来处理 C# 中的队列。 但是有没有办法删除队列中的最后一项? Dequeue 实际上是从顶部移除项目。
Queue
的全部目的是从上到下遍历集合。 如果您想要一个也允许从后面删除(或集合中的任何位置)的集合类型,请使用另一种集合类型,例如List<T>
。
也许您应该考虑使用堆栈而不是队列。
堆栈的工作原理类似队列但不是先入先出的行为,当你需要先解掉最后为对象堆栈使用
//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;
正如帕特里克所说,队列是先进先出的。 把它想象成一个打印机队列,进入打印机队列的第一页是第一个被打印出来的。
考虑使用列表而不是数组,我发现使用数组没有的一组扩展方法更容易操作列表。 http://www.dotnetperls.com/list
这是如何删除列表中最后一项的链接,该列表有几种不同的完成方式。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.