In C++, size() returns the number of elements currently stored in a std::stack. A new stack has size 0. Every push() adds one, and every pop() takes one away.
Duplicates count too. If you push the same number three times, the size is 3. The size says nothing about order beyond the count. You still use top() to see the newest element.
This function is a member function of std::stack<T>, declared in the <stack> header. It has been available since the first C++ standard, so every compiler supports it. You call it with a dot, for example st.size(...).
Syntax
Call size() on the stack. It takes no arguments and returns an unsigned number.
C++
std::stack<int> st;
st.push(5);
st.push(9);
std::size_t n = st.size(); // 2
Call
What it does
st.size()
Returns how many elements the stack holds. The stack is not changed.
The return type is size_type, an unsigned integer. Be careful when you subtract from it. If the stack is empty, st.size() - 1 does not give -1. It wraps around to a very large number. Check empty() first.
Each '(' is pushed. After the second open parenthesis the size becomes 2, which is recorded as the max depth.
Each ')' pops one opening mark when the stack is not empty. This keeps the depth correct.
When the loop ends the stack is empty, so no brackets were left open. size() tracked both the peak depth and the leftover count.
Frequently Asked Questions
It returns the number of elements currently in the stack, as an unsigned size_type. An empty stack has size 0.
Yes. A stack keeps every element you push, including equal values. Pushing 5 three times gives a size of 3.
No. Both only read. Only push(), emplace(), pop(), and swap() change the contents of the stack.
Both work, but empty() is clearer and just as fast. Use size() when you need the actual count, for example to track nesting depth.
size() returns an unsigned type. On an empty stack, 0 - 1 wraps around to a very large number instead of -1. Check empty() first, or compare without subtracting.