C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ stack top() functionC++ Stack top() function returns the value of the top element in the stack. The top element is the one which was recently added on the stack. The last added element is the top element. Of all the elements that are present in a stack the top element stands out and is more significant as all the major operations on the stack are performed at the top element. Be it push, pop or anything all the operations are done at the top most position. Syntaxvalue_type& top(); const value_type& top() const; ParametersThe function is used only for returning the value of the top element and hence takes nothing as parameters. The return type of the function is based on the value type of the stack. Return valueThe function returns the top element of the stack. Example 1//The program illustrates the use of top() function in stack to retrieve the value of top most element. #include <iostream> #include <stack> int main() { std::stack<int> newstack; newstack.push(24); newstack.push(80); newstack.top () +=20; std::cout <<"newstack.top() is modified to" <<newstack.top (); return 0; } Output: newstack.top() is modified to 100 Example 2//The program illustrates the use of top() function in stack to retrieve the value of top most element. #include <iostream> #include <stack> using namespace std; int main() { int result = 0; stack<int> newstack; newstack.push(2); newstack.push(7); newstack.push(4); newstack.push(5); newstack.push(3); while(!newstack.empty() ) { result = result + newstack.top(); newstack.pop(); } cout<<result; return 0; } Output: 21 Example 3//The program illustrates the use of top() function in stack to retrieve the value of top most element. #include <iostream> #include <stack> int main () { std::stack<int> newstack; newstack.push(9); newstack.push(14); std::cout << "newstack.top() is " << newstack.top() << '\n'; return 0; } Output: newstack.top() is 14 ComplexityThe complexity of the function is constant. The function only retrieves the value of the top element and does not take any extra time or space. Data racesThe function accesses the container, and retrieves the element which was last inserted. The top most element of the stack is given. Exception SafetyGuarantee as equivalent to the operations that are performed on the underlying container object is provided.
Next TopicC++ Stack
|