问题描述
可能的重复:
C++ STL栈问题:为什么栈为空pop()不抛出异常?
在C++中设计堆栈时,当堆栈为空时pop()方法(或front()方法)应该返回什么?以下哪个设计更好?
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?
- 抛出异常
- 未定义,但要求用户在调用pop() 之前调用isempty()方法进行检查
- 返回一个布尔代码,同时使用一个额外的参数(一个引用)来传递弹出的元素
- 定义一个唯一的空元素
- Throw an exception
- Undefined, but require the user calling isempty() method to check before calling pop()
- Return a bool code, while using an extra parameter (a reference) to pass the popped element
- Define an unique empty element
<小时>
好吧,我看到我的问题不是那么清楚,让我尝试重写它:
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".
推荐答案
契约式编程风格是,非空堆栈是调用 pop<的先决条件/code>,并且在不满足其先决条件的情况下调用方法会产生未定义结果.我的实现会抛出一个
std::logic_error
,但这不是必需的.在 C 中,我的实现将通过 assert
来abort
.
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
.
pop
的调用者负责确保在调用pop
之前栈不为空的前提条件成立.因此,堆栈应该有一个 isEmpty
方法供调用者检查.
The caller of pop
is responsible for ensuring that the precondition that the stack is not empty holds before calling pop
. The stack should therefore have an isEmpty
method for the caller to check.
这篇关于当堆栈为空时,'pop()' 方法应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!