In C++, the Standard Template Library (STL) includes various data structures and their respective algorithms that help make programming easier. One of the simplest and most common data structures is the stack. The stack is classified as an abstract data type (ADT) because data can only be added or removed from one side of the structure (the top of the stack).
In the C++ programming language , the stack top function returns the value of the top element in the stack. The top element is the element that was recently added to the stack. Among all the elements that are available in a stack , the top element is the most significant element because all main stack operations, such as push, pop, and top, are performed at the top position. Every insert or delete operation affects only this topmost element, which follows the Last In, First Out (LIFO) rule.
Syntax
It has the following syntax:
value_type& top();
const value_type& top() const;
In this syntax,
Parameters: The function is commonly utilized to return the value of the top element, and hence it doesn't take any parameters. The return type of the function is based on the value type of the stack.
Return value: The function returns the top element of the stack.
C++ Stack top function Example
Let us take an example to demonstrate how to retrieve the value of the last element using the stack top function in C++.
Example
#include <iostream>
#include <stack>
using namespace std; //using standard namespace
int main() //main function
{
stack<int> newst;
//using push() function
newst.push(24);
newst.push(80);
//using top() function
newst.top () +=20;
cout <<"The newst.top() is modified to" <<newst.top ();
return 0;
}
Output:
The newst.top() is modified to 100
Explanation:
In this example, we have created a stack named newst, where we have taken two elements (24 and 80) using the push function. After that, we have utilized the top function to access the topmost element (80) and increase its value by 20, which makes it 100. Finally, it prints the modified top element using the cout function on the console.
C++ Example to Calculate the Sum of Elements using the stack::top with the pop function
Let us take an example to illustrate how to calculate the sum of elements using the stack::top and the pop function in C++.
Example
#include <iostream>
#include <stack>
using namespace std; //using standard namespace
int main() //main function
{
int result = 0;
stack<int> newst;
//using the push function
newst.push(2);
newst.push(7);
newst.push(4);
newst.push(5);
newst.push(3);
while(!newst.empty() )
{
// using the top() function
result = result + newst.top();
newst.pop();
}
cout<<result;
return 0;
}
Output:
Explanation:
In this example, we have taken several integers that are pushed onto the stack. After that, we use the while loop that runs until the stack becomes empty. It repeatedly accesses the top element using the top function, adding it to the variable result, and removing it with the pop function. After all elements are processed, the final sum of the stack elements (21) is displayed on the screen.
C++ Example to Access the Top Element of a Stack Using the top Function
Let us consider an example that demonstrates how to access the top element of the stack using the top function in C++.
Example
#include <iostream>
#include <stack>
using namespace std; //using standard namespace
int main () //main function
{
stack<int> newst;
//using the push function
newst.push(9);
newst.push(14);
//using top() function
cout << "newst.top() is " << newst.top() << '\n';
return 0;
}
Output:
newstack.top() is 14
Explanation:
In this example, we have created a stack named newst, and then we inserted two elements (9 and 14) using the push function. After that, we have utilized the top function to access the element at the top of the stack. Finally, it prints the top element using the cout function.
Complexity Analysis
In the C++ programming language, the time complexity of the stack top function is constant complexity O(1). The top function only retrieves the value of the top element and does not take any extra time or space.
Use cases of the Stack top Function
There are several use cases of the stack top function in C++. Some of them are as follows:
- The stack top function is commonly utilized in algorithms to evaluate postfix, prefix, or infix mathematical expressions.
- It is utilized in those applications, like text editors, that use stacks to keep track of previous states. For example, the top function provides the current state.
- It is also utilized in compilers that rely on stacks to ensure balanced parentheses and the nesting of statements.
- If we want to solve mazes or find paths, the top function allows us to retrieve the last move made before backtracking.
- When we simulate function calls, the top function gives the current execution context.
Conclusion
In conclusion, the stack::top function in C++ is an efficient member function of the stack container. It allows us to gain access to the last inserted (top) element on the stack without removing it from the stack. It allows for logical and efficient manipulation of data using a last-in, first-out (LIFO) method.
In C++, the top function allows us to inspect the current "state" of the stack at any time. It also possesses read and write capabilities to allow for flexibility in various real-world scenarios.
C++ Stack top Function FAQs
1) What is the function of the stack::top function in C++?
The stack::top function in C++ provides a reference to the top element in the stack. We can read or change the element without removing it from the stack. It is most frequently called to look at the most recent value added to the stack.
2) Can we change the element that is returned by the stack top function in C++?
Yes. The top function returns a reference that allows us to directly change the element at the top of the stack. The only restriction of the top function is that if the stack was created as const, we can only read (access) the value and not modify it.
3) What happens if we call stack top on an empty stack in C++?
If we call the top function on an empty stack, it can lead to undefined behavior, a crashing program, and garbage output. We should always check the stack.empty function before accessing the top element.
4) Is the stack top an efficient operation in C++?
Yes, it is a very efficient operation. The time complexity of stack::top is constant time complexity, i.e., O(1).
5) Can we use the stack top function with const stacks in C++?
Yes, there is also a const version of the top function called const_reference top const. It allows us to access the top element on a const stack, but it will not provide modification access.