当堆栈为空时,在(模板化的)堆栈弹出方法中该怎么做? [英] What to do in a (templated) stack pop method when the stack is empty?
问题描述
我编写了一个模板化容器类,它采用模板参数的类型和模板.
I have written a templatized container class that takes type and template of template parameter.
template<class type, template<typename...> class Seq>
class stack1
{
private:
int count;
int size;
Seq<type> st;
//Seq<string> str;
public:
stack1(size_t size):size(100), count(-1){ }
void push(type elem);
type pop();
};
template<class type, template<typename...> class Seq>
type stack1<type, Seq>::pop()
{
if (count < 0)
{
cout << "stack1 is empty," << endl;
/*How to handle this condition.*/
}
else
{
type elem;
elem = st.back();
st.pop_back();
count--;
return elem;
}
}
我的问题是,在pop函数中,当容器对象为空时,我应该如何处理错误场景.在这种情况下,我想返回一些默认值,例如0/-1 如果容器是 int 或 ""/null 如果它是字符串或 0.0 如果它是浮点...类似的东西.
my question is , in the pop function how should I handle the error scenario when the container object is empty. I want to return some default value in that case, e.g. 0/-1 if the container is int or ""/null if it is string or 0.0 in case it is float... something like that.
推荐答案
@RSahu 的建议很好.
@RSahu's suggestion is a fine thing to have.
另一种可能是更改 pop()
函数的签名:
An alternative could be changing the signature of the pop()
function from:
type pop();
到
std::optional<type> pop();
并在堆栈为空时返回 std::nullopt
,或者在通常情况下返回一个包装值:
and returning std::nullopt
if the stack is empty, or a wrapped value in the usual case:
if (count < 0) {
return std::nullopt;
}
注意std::optional
是C++17语言标准中引入的;在 C++14 中,您将其作为 std::experimental::optional
,或者您可以将 boost::optional
用于 C++11 及更早版本.
Note that std::optional
is introduced in the C++17 language standard; in C++14 you have it as std::experimental::optional
, or you can use boost::optional
for C++11 and earlier.
PS:当元素计数实际上为 0 时,将计数设为 -1 是个坏主意 - 非常混乱!
PS: It's a bad idea to have count be -1 when the element count is actually 0 - very confusing!
这篇关于当堆栈为空时,在(模板化的)堆栈弹出方法中该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!