stack::swap() คืออะไร?
swap() เป็น member function ของ std::stack สลับเนื้อหาของ 2 stack **แบบทุกตัว (entire contents)** ใน O(1) (constant time)
Syntax
void swap(stack<T, Container>& other);
Parameters
other- stack อีกตัวที่ต้องการสลับ (ต้องเป็น type และ container เหมือนกัน)
Return Value
ไม่คืนค่า (void)
ตัวอย่าง
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> odd, even;
odd.push(1); odd.push(3); odd.push(5); // top=5
even.push(2); even.push(4); even.push(6); // top=6
cout << "Before swap:\n";
cout << "odd: "; while(!odd.empty()) { cout << odd.top() << " "; odd.pop(); } // 5 3 1
cout << "\neven: "; while(!even.empty()) { cout << even.top() << " "; even.pop(); } // 6 4 2
// ต้องสร้างใหม่เพื่อ demo swap
odd.push(1); odd.push(3); odd.push(5);
even.push(2); even.push(4); even.push(6);
odd.swap(even);
cout << "\n\nAfter swap:\n";
cout << "odd: "; while(!odd.empty()) { cout << odd.top() << " "; odd.pop(); } // 6 4 2
cout << "\neven: "; while(!even.empty()) { cout << even.top() << " "; even.pop(); } // 5 3 1
return 0;
}
Output
Before swap: odd: 5 3 1 even: 6 4 2 After swap: odd: 6 4 2 even: 5 3 1
Non-member swap (C++11)
std::swap(odd, even); // เรียก odd.swap(even) ให้อัตโนมัติ
ประโยชน์ของ swap()
- O(1) - แค่สลับ pointer/metadata ของ underlying container ไม่ copy element
- ใช้ในการ implement move semantics, clear stack เร็ว (
stack<T>().swap(st)) - Exception safe (no-throw)
ข้อจำกัด
- ทั้ง 2 stack ต้องมี **template parameters เหมือนกันทุกประการ** (T และ Container)
- ไม่สามารถ swap stack
กับ stack หรือ stack > ได้
สรุป
stack::swap(other) สลับเนื้อหา 2 stack แบบ O(1) ต้องเป็น type เหมือนกันทุกประการ ใช้ได้กับ non-member std::swap() ด้วย