stack::swap(other) ফাংশন দুটি স্ট্যাকের কন্টেন্ট এক্সচেঞ্জ করে। O(1) টাইম।
সিনট্যাক্স
stack_name.swap(other_stack); উদাহরণ
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> s1, s2;
s1.push(1); s1.push(2); s1.push(3); s1.push(4);
s2.push(5); s2.push(6); s2.push(7); s2.push(8);
s1.swap(s2);
cout << "s1: "; while(!s1.empty()){cout<<s1.top()<<" ";s1.pop();}
cout << "\ns2: "; while(!s2.empty()){cout<<s2.top()<<" ";s2.pop();}
// s1: 8 7 6 5
// s2: 4 3 2 1
}
আউটপুট
Elements in stack 1 are: 8 7 6 5 Elements in stack 2 are: 4 3 2 1