C++ stack top() Function
Example
Get the top element of a stack:
stack<string> cars;
cars.push("Volvo");
cars.push("BMW");
cars.push("Ford");
cars.push("Mazda");
cout << cars.top();
Definition and Usage
The top() function returns the top element of a stack. This is the last element that was added.
You can also use it to change the top element, like cars.top() = "Tesla";.
The top function is defined in the <stack> header file.
Note: Do not call top() on an empty stack. Check with empty() first.
Syntax
stack.top();
Parameter Values
None.
Technical Details
| Returns: | A reference to the top element of the stack. |
|---|
Related Pages
Read more about stacks in our Stacks Tutorial.