#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; }Please note that is isn't thread-safe - in a multi-threaded program another thread might add/remove items between the size() and top() calls.
Programming Tips - C++: How can I avoid pop()ing an empty std::stack ?
Date: 2016aug11
Language: C++
Q. C++: How can I avoid pop()ing an empty std::stack ?
A. Check size() first, like this: