บทความนี้แสดงการทำงานของฟังก์ชัน list::swap() ใน C++ STL
List ใน STL คืออะไร?
List เป็นคอนเทนเนอร์ที่รองรับการแทรกและลบข้อมูลได้ในเวลาคงที่ (constant time) ที่ตำแหน่งใดก็ได้ในลำดับ List ถูกนำไปใช้งานเป็น doubly linked list ทำให้จัดสรรหน่วยความจำแบบไม่ต่อเนื่องได้ List ให้ประสิทธิภาพการแทรก ดึง และย้ายข้อมูลที่ตำแหน่งใดก็ได้ในคอนเทนเนอร์ดีกว่า array, vector และ deque อย่างไรก็ตาม การเข้าถึงข้อมูลโดยตรง (random access) ใน List ช้ากว่า และ List คล้ายกับ forward_list แต่ forward_list เป็น singly linked list จึงวนลูปได้เฉพาะทิศทางไปข้างหน้าเท่านั้น
list::swap() คืออะไร?
ฟังก์ชันนี้ใช้สำหรับ สลับองค์ประกอบระหว่างสอง list ที่มีชนิดข้อมูลและขนาดเหมือนกัน
ไวยากรณ์ (Syntax)
listname1.swap(listname2);
ตัวอย่างการใช้งาน
Input List1: 50 60 80 90 List2: 90 80 70 60 Output After swapping: List1: 90 80 70 60 List2: 50 60 80 90
แนวทางการใช้งาน
- สร้าง list 2 ตัว
- พิมพ์ list ทั้งสอง
- เรียก swap()
- พิมพ์ list ทั้งสองหลังสลับ
ตัวอย่างโค้ดเต็ม 1
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> list1 = { 10, 20, 30, 40, 50 };
cout << "List1: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
list<int> list2 = { 40, 50, 60, 70, 80 };
cout << "\nList2: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
// สลับ
list1.swap(list2);
cout << "\nAfter swapping List1 is: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
cout << "\nAfter swapping List2 is: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Input - List1: 10 20 30 40 50 List2: 40 50 60 70 80 Output - After swapping List1 is: 40 50 60 70 80 After swapping List2 is: 10 20 30 40 50
ตัวอย่างโค้ดเต็ม 2
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> list1 = { 11, 12, 13, 14, 15 };
cout << "List1: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
list<int> list2 = { 16, 17, 18, 19, 20 };
cout << "\nList2: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
list1.swap(list2);
cout << "\nAfter swapping List1 is: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
cout << "\nAfter swapping List2 is: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Input - List1: 11 12 13 14 15 List2: 16 17 18 19 20 Output - After swapping List1 is: 16 17 18 19 20 After swapping List2 is: 11 12 13 14 15