บทความนี้แสดงการทำงานของโอเปอเรเตอร์ list::operator= ใน 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::operator= ใช้ทำอะไร?
โอเปอเรเตอร์นี้ใช้สำหรับ กำหนดค่าใหม่ให้ list โดยแทนที่องค์ประกอบเดิม และปรับขนาดของ list ใหม่ให้สอดคล้องกับเนื้อหาใหม่ Container ต้นทางที่นำข้อมูลมาต้องมีชนิดข้อมูลเดียวกัน
ไวยากรณ์ (Syntax)
listname1 = listname2;
ตัวอย่างการใช้งาน
Input List1: 50 60 80 90 List2: 90 80 70 60 Output List1: 90 80 70 60 Input List1: E N E R G Y List2: C A P T I O N Output List1: C A P T I O N
แนวทางการใช้งาน
- สร้าง list 2 ตัว
- ใช้ operator =
- พิมพ์ list ใหม่
การทำงานคล้าย swap() แต่ operator = จะคัดลอกข้อมูลจาก list2 ไป list1 (list2 ไม่เปลี่ยน)
ตัวอย่างโค้ดเต็ม 1
#include <iostream>
#include <list>
using namespace std;
int main() {
// สร้าง list 2 ตัว
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 = list2
list1 = list2;
cout << "\nNew contents of List1 is: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Input - List1: 10 20 30 40 50 List2: 40 50 60 70 80 Output - New content of List1 is: 40 50 60 70 80
ตัวอย่างโค้ดเต็ม 2 (ใช้ char)
#include <iostream>
#include <list>
using namespace std;
int main() {
list<char> list1 = { 'C', 'H', 'A', 'R', 'G', 'E', 'R' };
cout << "List1: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
list<char> list2 = { 'P', 'O', 'I', 'N', 'T' };
cout << "\nList2: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
list1 = list2;
cout << "\nNew contents of List1 is: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Input - List1: C H A R G E R List2: P O I N T Output - New contents of List1 is: P O I N T