我正在尝试编写此 Coursera course example of Towers of Hanoi 中给出的 Cube、Stack 示例的实现代码学习更多 C++。
在stack.h
中我必须实现:
class Stack {
public:
void push_back(const Cube & cube);
Cube removeTop();
Cube & peekTop();
unsigned size() const;
friend std::ostream & operator<<(std::ostream & os, const Stack & stack);
private:
std::vector<Cube> cubes_;
};
我遇到的问题是 removeTop()
。我正在考虑如果堆栈( vector )为空,则返回 nullptr,因为对于空 vector ,pop_back 的行为未定义。
Calling pop_back on an empty container is undefined. Cpp Reference
inline Cube Stack::removeTop() {
if (!cubes_.empty()) {
Cube top_cube = cubes_.back();
cubes_.pop_back();
return top_cube;
}
else {
return nullptr;
}
}
但是,我在编译过程中遇到错误。
./stack.h:35:12: error: no viable conversion from returned value of type
'std::__1::nullptr_t' to function return type 'uiuc::Cube'
return nullptr;
如果无法返回 nullptr
,如何保护用户?我是否仅限于告诉用户该函数不应在空堆栈上调用并让他/她负责检查?
请您参考如下方法:
这正是异常(exception)的用途:
if (cubes_.empty())
throw std::runtime_error("stack underflow");
Cube top_cube = cubes_.back();
cubes_.pop_back();
return top_cube;
用 std::Optional
使这个问题变得复杂几乎可以肯定不是这里的正确答案。尝试从空堆栈中弹出意味着程序迷失了方向。这应该是一个硬错误,而不是被界面掩盖的错误,该界面显示“您可能有也可能没有这个,请稍后检查”。