ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของ Operator = (Assignment) สำหรับ Map ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
Map Assignment Operator (=) คืออะไร?
Operator = ใช้คัดลอก Elements จาก Map หนึ่งไปยังอีก Map หนึ่ง โดยทับทีเนื้อหาเดิมของ Map ปลายทาง
Syntax
map1 = map2;
Parameters
Map ซ้าย = ปลายทาง, Map ขวา = ต้นทาง เนื้อหาของ Map ขวาจะถูกคัดลอกไป Map ซ้าย
Return Value
ไม่มีค่าคืน (เป็น Operator ไม่ใช่ Function)
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP, temp;
TP.insert({2, 20});
TP.insert({1, 10});
TP.insert({3, 30});
TP.insert({4, 40});
TP.insert({6, 50});
temp = TP; // Assignment
cout << "\nData in map TP is: \nKEY\tELEMENT\n";
for (auto i = TP.begin(); i != TP.end(); ++i)
cout << i->first << '\t' << i->second << '\n';
cout << "\nData in copied map temp is : \nKEY\tELEMENT\n";
for (auto i = temp.begin(); i != temp.end(); ++i) // ใช้ temp ไม่ใช่ TP
cout << i->first << '\t' << i->second << '\n';
return 0;
}
ผลลัพธ์
Data in map TP is: MAP_KEY MAP_ELEMENT 1 10 2 20 3 30 4 40 6 50 Data in copied map temp is : MAP_KEY MAP_ELEMENT 1 10 2 20 3 30 4 40 6 50
หมายเหตุ
ตัวอย่างโค้ดต้นฉบับมี Bug: ลูปที่สองใช้ TP.begin() แทน temp.begin() แก้ไขแล้วในโค้ดข้างต้น