Bhupesh Pant
Bhupesh Pant

Reputation: 4349

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;
    }
}

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.

Upvotes: 0

Views: 330

Answers (2)

einpoklum
einpoklum

Reputation: 131996

@RSahu's suggestion is a fine thing to have.

An alternative could be changing the signature of the pop() function from:

type pop();

to

std::optional<type> pop();

and returning std::nullopt if the stack is empty, or a wrapped value in the usual case:

if (count < 0) {
    return std::nullopt;
}

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: It's a bad idea to have count be -1 when the element count is actually 0 - very confusing!

Upvotes: 3

R Sahu
R Sahu

Reputation: 206697

One way to deal with it will be to throw an exception.

if (count < 0)
{
    throw std::out_of_range("stack1 is empty");
}

I would strongly discourage using std::cout to print a message to the terminal at that place. Use of std::cout in implementations of data structures is a poor programming practice.

Upvotes: 3

Related Questions