应该怎样'流行()方法返回时,堆栈是空的? [英] What should the 'pop()' method return when the stack is empty?

查看:100
本文介绍了应该怎样'流行()方法返回时,堆栈是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/4892108/c-stl-stack-question-why-does-pop-not-throw-an-exception-if-the-stack-is-emp\">C++ STL栈的问题:为什么流行()如果堆栈是空的不是抛出一个异常

在设计C ++中的堆栈,应该在弹出()方式(或前()法)返回时,堆栈是空的?以下哪项设计的比较好?

When designing a stack in C++, what should the pop() method (or front() method) return when the stack is empty? Which of the following design is better?


  1. 抛出一个异常

  2. 不定,但需要用户调用的的isEmpty()方法来检查调用的 POP()

  3. 返回一个布尔值code,而使用一个额外的参数(参考)来传递弹出元素

  4. 定义一个独特的空元素

  1. Throw an exception
  2. Undefined, but require the user calling isempty() method to check before calling pop()
  3. Return a bool code, while using an extra parameter (a reference) to pass the popped element
  4. Define an unique empty element

OK,我看到我的问题是没有说清楚,让我尝试把它改写:


OK, I see that my question is not that clear, let me try to rewrite it:

有能够基于像栈,队列链表上实现某些数据结构,和他们每个人都有一个方法返回前元件(或尾巴)。

There are some data structures which can be implemented based on linked list like stack, queue, and each of them has a methods returning the front element (or the tail).

我想知道,是否有关于设计时数据为空关于本案这样的方法原则的任何指引。

I want to know, is there any principle guideline about designing such a method regarding the case when the data is empty.

和我更好的定义是易于正确使用,而难以错误使用。

And my definition of better is "easy to use correctly and hard to use incorrectly".

推荐答案

编程按合同书样式将是具有非空栈是的 $ P $调用的pcondition 弹出,并没有调用满足其preconditions的方法有一个未定义的结果。我的实现将抛出一个的std :: logic_error ,但不会是的需要的。在C语言中,我会实施中止通过断言

The programming-by-contract style would be that having a non-empty stack is a precondition of calling pop, and that calling a method without meeting its preconditions has an undefined outcome. My implementation would throw a std::logic_error, but that would not be required. In C, my implementation would abort via assert.

的调用者弹出负责确保precendition堆栈是不是空舱之前调用弹出。因此,堆栈应该有来电来检查的isEmpty 方法。

The caller of popis responsible for ensuring that the precendition that the stack is not empty holds before calling pop. The stack should therefore have an isEmpty method for the caller to check.

这篇关于应该怎样'流行()方法返回时,堆栈是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆