stack swap() in C++ STL

Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only.


This function is used to swap the contents of one stack with another stack of same type but the size may vary.

Syntax :


Parameters: The name of the stack with which the contents have to be swapped.

Result: All the elements of the 2 stack are swapped.


contents of the stack from top to bottom are
Input  : mystack1 = {4, 3, 2, 1}
         mystack2 = {9, 7 ,5, 3}
Output : mystack1 =  9, 7, 5, 3
         mystack2 =  4, 3, 2, 1

Input  : mystack1 = {7, 5, 3, 1}
         mystack2 = {8, 6, 4, 2}
Output : mystack1 =  8, 6, 4, 2
         mystack2 =  7, 5, 3, 1

Note: In stack container, the elements are printed in reverse order because the top is printed first then moving on to other elements.





// CPP program to illustrate
// Implementation of swap() function
#include <stack>
#include <iostream>
using namespace std;
int main()
        // stack container declaration
    stack<int> mystack1;
    stack<int> mystack2;
       // pushing elements into first stack
       // pushing elements into 2nd stack
        // using swap() function to swap elements of stacks
        // printing the first stack
    cout<<"mystack1 = ";
     while (!mystack1.empty()) {
        cout<<<<" ";
        // printing the second stack
    cout<<endl<<"mystack2 = ";
    while (!mystack2.empty()) {
        cout<<<<" ";
    return 0;



mystack1 = 9 7 5 3
mystack2 = 4 3 2 1

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : terror19_7

Article Tags :
Practice Tags :


Please write to us at to report any issue with the above content.