stack::swap() hoán đổi nội dung của 2 stack cùng kiểu.
Cú pháp
stack1.swap(stack2);
Ví dụ
#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();}
return 0;
}
Đầu ra
s1: 8 7 6 5 s2: 4 3 2 1