Dave's Brain

Browse - Programming Tips - How can I avoid pop()ing an empty std::stack ?

Date: 2016aug11
Language: C++

Q.  How can I avoid pop()ing an empty std::stack ?

A.  Check size() first, like this:

#include <string> #include <stack> #include <iostream> std::stack<std::string> mystack; if (mystack.size() == 0) { std::cout << "Stack is empty" << std::endl; } else { std:string str = mystack.top(); mystack.pop(); std::cout << "Popped " << str << std::endl; }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.