C++ stack swap() Function
Example
Swap the contents of two stacks:
stack<string> cars;
stack<string> fruits;
cars.push("Volvo");
fruits.push("Apple");
cars.swap(fruits);
cout << cars.top() << "\n";
cout << fruits.top();
Definition and Usage
The swap() function swaps the contents of two stacks. After the swap, each stack has the elements that the other stack had before.
Both stacks must store the same type of data, but they can have a different number of elements.
The swap function is defined in the <stack> header file.
Syntax
stack.swap(stack<type> other);
<type> refers to the type of the data that the stack contains.
Parameter Values
| Parameter | Description |
|---|---|
| other | Required. Another stack with the same type of data. |
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about stacks in our Stacks Tutorial.