CKTIS / C++
std::stack — a LIFO container adaptor
std::stack from <stack> provides a LIFO stack: the most recently added element is removed first. The adaptor supports adding elements, inspecting the top, and removing it, but exposes neither iterators nor indexed access.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <stack>
std::stack<T> name;
std::stack<T, Container> name;std::stack<T, Container> is a container adaptor implementing LIFO (last in, first out). It stores elements in an underlying container, which defaults to std::deque<T>. std::vector<T> or std::list<T> can also be used; the container must support back(), push_back() and pop_back(). T must match the container's element type.
push(value) adds an element at the top, while emplace(args...) constructs one there from the supplied arguments. top() accesses the top element without removing it. The non-const overload returns Container::reference, and the const overload returns Container::const_reference. These need not be C++ reference types: with std::vector<bool> as the underlying container, the non-const overload returns a proxy object and the const overload returns a bool by value.
pop() removes the top and returns void. To keep the value, copy or move it into an independent object of type T before calling pop(). With std::vector<bool>, store the result in a bool, for example bool value = stack.top();. Copying the proxy does not preserve an independent bool value. empty() checks whether the stack is empty, and size() reports its element count.
Ensure the stack is not empty before calling top() or pop(); in C++23, calling either on an empty stack has undefined behavior. Do not use a reference or proxy that refers to a removed element. The adaptor exposes neither iterators nor operator[]; the example reads and removes successive elements, draining the stack.
This entry targets C++23; the repository compiler flag does not attest the production runtime. The linked document is an evolving working draft, not a frozen C++23 text; the example does not require later extensions.
Examples
#include <iostream>
#include <stack>
int main() {
std::stack<int> values;
values.push(10);
values.push(20);
values.emplace(30);
std::cout << "size: " << values.size() << '\n';
while (!values.empty()) {
std::cout << values.top() << '\n';
values.pop();
}
std::cout << "empty: " << std::boolalpha << values.empty() << '\n';
}
Result
size: 3 30 20 10 empty: true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.