ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::at() และ map::swap() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::at()
ดูรายละเอียดในบทความก่อนหน้า (ID 1004080319) - ใช้เข้าถึง Value โดย Key โยน Exception ถ้า Key ไม่มี
map::swap() คืออะไร?
map::swap() เป็นฟังก์ชันใน header <map> ใช้สลับเนื้อหาของ Map 2 ตัว สลับได้แม้ขนาดต่างกัน
Syntax
map_name.swap(map& map_name2);
Parameters
map_name2 − Map อีกตัวที่ต้องการสลับ
Return Value
ไม่มีค่าคืน (void)
ตัวอย่าง map::swap()
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_1;
map<int, int> TP_2;
TP_1[1] = 10; TP_1[2] = 20; TP_1[3] = 30; TP_1[4] = 40;
TP_2[5] = 50; TP_2[6] = 60; TP_2[7] = 70;
swap(TP_1, TP_2); // หรือ TP_1.swap(TP_2);
cout << "Elements of TP_1 after swap:\n\tKEY\tELEMENT\n";
for (auto i = TP_1.begin(); i != TP_1.end(); i++)
cout << "\t" << i->first << "\t" << i->second << '\n';
cout << "Elements of TP_2 after swap:\n\tKEY\tELEMENT\n";
for (auto i = TP_2.begin(); i != TP_2.end(); i++)
cout << "\t" << i->first << "\t" << i->second << '\n';
return 0;
}
ผลลัพธ์
Elements of TP_1 after swap: KEY ELEMENT 5 50 6 60 7 70 Elements of TP_2 after swap: KEY ELEMENT 1 10 2 20 3 30 4 40
สรุป
at()= เข้าถึง Value โดย Key (ปลอดภัยกว่า operator[])swap()= สลับเนื้อหา 2 Map ได้ใน O(1) โดยไม่ต้องคัดลอก Element ทีละตัว