std::stack::top(3)
Hey bestie π welcome to the std::stack::top page, section 3, from the C++ Standard Libary manual. We're about to look at the element literally sitting on top of the stack β main character energy only π.
π NAME π
std::stack::top - std::stack::top
(Yes, the NAME section says it twice. She said what she said π )
β¨ Synopsis β¨
reference top();
const_reference top() const;
Okay so here's the vibe: it returns a reference to the top element in the stack. That's the most recently pushed element. This element will be removed on a call to pop(). Effectively calls c.back().
πΈ Parameters πΈ
(none) β no parameters. Not a single one. Low-maintenance icon behavior π«Ά.
π¦ Return value π¦
Reference to the last element.
π Complexity π
Constant.
π Example π
The original says // Run this code, so run it, bestie π:
// Run this code
#include <iostream>
#include <stack>
void reportStackSize(const std::stack<int>& s)
{
std::cout << s.size() << " elements on stack\n";
}
void reportStackTop(const std::stack<int>& s)
{
// Leaves element on stack
std::cout << "Top element: " << s.top() << '\n';
}
int main()
{
std::stack<int> s;
s.push(2);
s.push(6);
s.push(51);
reportStackSize(s);
reportStackTop(s);
reportStackSize(s);
s.pop();
reportStackSize(s);
reportStackTop(s);
}
β Output β
3 elements on stack
Top element: 51
3 elements on stack
2 elements on stack
Top element: 6
π See also π
pushβ inserts element at the top (public member function)popβ removes the top element (public member function)
Cute sign-off: source http://cppreference.com, version/date 2024.06.10, page std::stack::top(3). Mwah πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms