当堆栈为空时,'pop()' 方法应该返回什么?

What should the #39;pop()#39; method return when the stack is empty?(当堆栈为空时,pop() 方法应该返回什么?)

本文介绍了当堆栈为空时,'pop()' 方法应该返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
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?

  1. 抛出异常
  2. 未定义,但要求用户在调用pop()
  3. 之前调用isempty()方法进行检查
  4. 返回一个布尔代码,同时使用一个额外的参数(一个引用)来传递弹出的元素
  5. 定义一个唯一的空元素
  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, 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 中,我的实现将通过 assertabort.

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 popis 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()' 方法应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当堆栈为空时,'pop()' 方法应该返回什么?

基础教程推荐