In C++11, swap()exchanges everything inside two std::stack objects. After a.swap(b), stack a holds what b had, and stack b holds what a had.
The swap is fast, because the stacks just trade their inner containers. No element is copied one by one. Both stacks must have the same type, which includes the element type and the underlying container. You can also write std::swap(a, b).
This function is a member function of std::stack<T>, declared in the <stack> header. It needs C++11 or newer (-std=c++11). You call it with a dot, for example st.swap(...).
Syntax
Call swap() on one stack and pass the other stack. Or call the non-member std::swap with both.
C++
std::stack<int> a;
std::stack<int> b;
a.push(3);
b.push(20);
a.swap(b); // a now has 20, b now has 3
std::swap(a, b); // swaps them back
Call
What it does
a.swap(b)
Exchanges the contents of a and b. Nothing is returned.
std::swap(a, b)
The non-member version. It does the same thing and calls a.swap(b) inside.
Swapping does not change the LIFO order inside each stack, and it does not call top() or pop(). stack has no clear(), so swapping with an empty stack is a common way to empty it.
Library declarations
C++
void swap(stack& other) noexcept(/* see below */); // C++11
// Non-member overload (C++11):
template<class T, class Container>
void swap(stack<T, Container>& lhs, stack<T, Container>& rhs);
// stack<T, Container> from <stack>
// It swaps the underlying container c.
Parameters
Parameter
Description
other
Required. Another stack of the same type. It trades its contents with the stack you call swap() on.
Return Value
Return Value
Description
Nothing
swap() returns void. Both stacks are changed in place.
C++ Examples
Example 1 — Swap Two Stacks
Fill two stacks with different numbers. After swap(), the tops and sizes are exchanged.