Associative Array คืออะไร?
ใน C++ เรียกว่า std::map หรือ std::unordered_map เป็นโครงสร้างข้อมูล Key-Value Pair ที่ Key สามารถเป็นชนิดข้อมูลใดก็ได้ (string, int, float, custom class)
ต่างจากอาร์เรย์ทั่วไปที่เข้าถึงด้วย index แบบ integer
ตัวอย่าง: Map ระหว่างชื่อรถจักรยานยนต์และความเร็วสูงสุด
| Key (Bike) | Value (Top Speed) |
|---|---|
| Ninja | 290 |
| S1000rr | 310 |
| Bullet | 127 |
| Duke | 135 |
| R1 | 286 |
ตัวอย่างโค้ด C++ (std::map)
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// สร้าง map โดยใช้ initializer list
map<string, int> speed = {
{"ninja", 290},
{"s1000rr", 310},
{"bullet", 127},
{"Duke", 135},
{"R1", 286}
};
// วนลูปแสดงค่าทั้งหมด (จัดเรียงตาม key อัตโนมัติ)
cout << "Top speeds:" << endl;
for (const auto& pair : speed) {
cout << pair.first << " → " << pair.second << " km/h" << endl;
}
// เข้าถึงค่าผ่าน key
cout << "\nTop speed of bullet: " << speed["bullet"] << " km/h" << endl;
// ตรวจสอบว่ามี key หรือไม่
if (speed.count("Hayabusa"))
cout << "Hayabusa: " << speed["Hayabusa"] << endl;
else
cout << "Hayabusa not found" << endl;
// เพิ่ม/แก้ไขค่า
speed["Hayabusa"] = 312;
speed["ninja"] = 300; // อัปเดตค่า
return 0;
}
ผลลัพธ์
Top speeds: Duke → 135 km/h R1 → 286 km/h bullet → 127 km/h ninja → 290 km/h s1000rr → 310 km/h Top speed of bullet: 127 km/h Hayabusa not found
Map vs Unordered Map
| คุณสมบัติ | std::map | std::unordered_map |
|---|---|---|
| ลำดับข้อมูล | จัดเรียงตาม key (Red-Black Tree) | ไม่จัดเรียง (Hash Table) |
| ค้นหา/แทรก/ลบ | O(log n) | O(1) เฉลี่ย |
| ความต้องการของ Key | ต้องมี operator< | ต้องมี hash function |