C++ stack pop() Function
Example
Print and remove the elements of a stack, one by one:
stack<string> cars;
cars.push("Volvo");
cars.push("BMW");
cars.push("Ford");
while (!cars.empty()) {
cout << cars.top() << "\n";
cars.pop();
}
Definition and Usage
The pop() function removes the top element of a stack. This is the last element that was added.
It does not return the removed element. Use top() first if you need its value. In the example, the loop runs until the stack is empty, so the elements are printed in the opposite order of how they were added.
The pop function is defined in the <stack> header file.
Note: Do not call pop() on an empty stack. Check with empty() first.
Syntax
stack.pop();
Parameter Values
None.
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about stacks in our Stacks Tutorial.