C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Stack empty() functionC++ Stack empty() function is used for testing whether the container is empty or not. In many cases, before extracting the actual elements from the stack, programmers give preference to check whether the stack does have some elements or not. Doing so is advantageous regarding memory and cost. Syntaxbool empty() const; ParametersThere are no parameters. Since the function is used only for testing purpose, so it is directly applied to the stack. Hence no arguments are passed. Return valueIf the container under reference is empty, then the method returns 'true' else returns 'false'. The method is used only for the purpose of testing so based on the test results values are returned. Example 1//The program given below is used for the detection of emptiness of a container. #include <iostream> #include <stack> int main() { std::stack<int> newstack; int sum=0; for (int j=1; j<=10; j++) newstack.push(j); while (!newstack.empty ()) { sum += newstack.top (); newstack.pop (); } std::cout << "Result is: " << sum; return 0; } return 0; } Output: Result is: 55 Example 2//The program given below is used for the detection of emptiness of a container. #include <iostream> #include <stack> using namespace std; int main() { std::stack<int> newstack; newstack.push(69); //Checking whether the stack is empty if(newstack.empty()) { cout<<"The stack is empty, insert some elements to keep going"; } else { cout<<"Elements are present in the stack"; } return 0; } Output: Elements are present in the stack ComplexityThe function is used only for the detection of emptiness of the container, hence accepts no parameters and has constant complexity. Data racesOnly the container is accessed. The stack is accessed to check for the presence of elements. Not all the elements are accessed by this function but a glance is made to check if the container is totally empty or has some presence. Exception SafetyGuarantee as equivalent to the operations that are performed on the underlying container object is provided.
Next TopicC++ Stack
|