当数据结构为空时返回什么?
我正在实现一个通用优先级队列作为家庭作业项目的一部分。我想知道当 PriorityQueue 为空时返回什么。我无法返回 null。
处理这种情况的最佳方法是什么?实现此类数据结构时最好的设计选择是什么?
class PQueue<T> : IPQueue<T>
{
T[] items;
//..
public T RemoveMax()
{
if(heapSize < 1) //Heap Empty
return default(T);
T max = items[0];
//..
return max;
}
}
I am implementing a generic Priority Queue as part of a homework project. I am wondering what to return when the PriorityQueue is empty. I could not return null.
What is the best method to handle this case? What is the best design choice when implementing such datastructures?
class PQueue<T> : IPQueue<T>
{
T[] items;
//..
public T RemoveMax()
{
if(heapSize < 1) //Heap Empty
return default(T);
T max = items[0];
//..
return max;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会在此处的框架类中寻找指导,即
Queue
- 如果您尝试从空队列中取出一个项目,它会抛出InvalidOperationException
。只有当您允许消费者访问队列中的项目数量或至少队列是否为空时,这才有意义,即:I would look for guidance in the framework classes here, i.e.
Queue<T>
- which throws anInvalidOperationException
if you try and dequeue an item from an empty queue. This only makes sense though if you give consumers access to the number of items in the queue or at least if the queue is empty or not, i.e.:抛出异常。
QueueEmptyException(“优先级队列为空”)
类似的东西。
Throw an exception.
QueueEmptyException("Priority Queue is Empty")
Something like that.
抛出异常的另一种方法是使用空对象模式(wiki)返回一个 wiki 。 T>那“什么也不做”。
这看起来似乎是不必要的复杂化,但这将帮助您避免对队列访问进行 try/catch 操作。它还避免了使用异常来处理有效行为的反模式,如果您的队列经常为空,这也可能会带来性能问题,因为异常处理“缓慢”。
An alternative to throwing an exception is to use the Null Object Pattern (wiki) to return a <T> that "does nothing".
This may seem like unnecessary complication, but this will help you avoid try/catch operations on the queue access. It also avoids the anti-pattern of using exceptions to handle valid behaviour, and if your queue is often empty this could also pose performance issues, as exception handling is 'slow'.