std::stack::top(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

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