当堆栈为空时,在(模板化)堆栈弹出方法中该怎么办? [英] 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函数中,当容器对象为空时,我应该如何处理错误情况.在这种情况下,我想返回一些默认值,例如如果容器为int,则为0/-1;如果为字符串,则为"/null;如果为float,则为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;
}
请注意,在C ++ 17语言标准中引入了 std :: optional
;在C ++ 14中,您可以将其作为 std :: experimental :: optional
,或者对于C ++ 11和更早版本,可以使用 boost :: optional
.
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时,将count设为-1是一个糟糕的主意-非常令人困惑!
PS: It's a bad idea to have count be -1 when the element count is actually 0 - very confusing!
这篇关于当堆栈为空时,在(模板化)堆栈弹出方法中该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!