C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Stack size() FunctionC++ Stack size() function returns the number of stack elements. The number of stack elements is referred to the size of the stack. The size of the stack element is very important information as based on it we can deduce many other things such as the space required, etc. Syntaxsize_type size() const ParametersNo parameters are passed to the function; it simply gives the size of the stack under reference. Since the function is used to get an idea about the stack size there is no purpose of the argument in the program. Return valueThe number of elements in the stack is returned, which is a measure of the size of the stack. Hence the function has an integer return type as size is an int value. Example 1// A simple C++ to demonstrate the use of the size() function in the stack container. #include <iostream> #include <stack> using namespace std; int main() { std::stack<int> newstack; std::cout << "0. size: "<< newstack.size(); for(int j=0; j<5; j++) newstack.push(j); cout<<"\n"; std::cout<<"1. size: " << newstack.size(); newstack.pop(); cout<<"\n"; std::cout<<"2. size: "<< newstack.size(); return 0; } Output: 0. size: 0 1. size: 5 2. size: 4 Example 2// A simple C++ to demonstrate the use of the size() function in the stack container. #include <iostream> #include <stack> using namespace std; int main() { std::stack<int> newstack; newstack.push(23); newstack.push(46); newstack.push(69); cout << newstack.size(); return 0; } Output: 3 Example 3// A simple C++ to demonstrate the use of the size() function in the stack container. #include <iostream> #include <stack> int main() { std::stack<int> a,b; a.push(5); a.push(8); a.push(50); b.push(132); b.push(45); std::cout<<"Size of a: "<<a.size(); std::cout<<"\n Size of b:" <<b.size(); return 0; } Output: Size of a: 3 Size of b: 2 ComplexityThe complexity of the function is constant, the function only returns the size of the stack, which is measured by the number of elements. Data racesThe function accesses the container. The whole stack container is accessed by this function for the value of stack size. As size is measured by the total number of elements present in the stack so whole container is atleast once accessed. Exception SafetyGuarantee as equivalent to the operations that are performed on the underlying container object is provided.
Next TopicC++ Stack
|