How to swap stacks in C++

1 Answer

0 votes
#include <iostream>       
#include <stack>          

using namespace std; 

void printStack(stack<int> st) {
  while (!st.empty()) {
     cout << st.top() << ' ';
     st.pop();
  }
}

int main ()
{
    auto it1 = {1, 2, 3, 4, 5};
    stack<int> st1(it1);
     
    auto it2 = {9, 7, 0, 8};
    stack<int> st2(it2);
     
    st1.swap(st2);
      
    cout << "st1" << endl;
    printStack(st1);
      
    cout << endl << "st2" << endl;
    printStack(st2);
    
    return 0;
} 
   
   
   
/*
run:
   
st1
8 0 7 9 
st2
5 4 3 2 1 

*/

 



answered Apr 6, 2020 by avibootz
...