ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::insert() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::insert() คืออะไร?
map::insert() ใช้แทรก Element ใหม่เข้า Map เพิ่มขนาด Container ตรวจสอบ Key ซ้ำ: ถ้า Key มีอยู่แล้ว จะไม่แทรก
Map จัดเก็บ Element เรียงตาม Key ดังนั้น Element ใหม่จะไปวางที่ตำแหน่งที่เหมาะสมตาม Key
Syntax (3 รูปแบบ)
1. map_name.insert({key& k, value_type& val});
2. map_name.insert(iterator& it, {key& k, value_type& val}); // with hint
3. map_name.insert(iterator& first, iterator& last); // range insert
Parameters
- k − Key ของ Element (ต้อง Unique)
- val − Value ที่จะแทรก
- it − Iterator hint ตำแหน่งที่คาดว่าจะแทรก (เพื่อประสิทธิภาพ)
- first, last − Range ของ Elements ที่จะแทรกหลายตัวพร้อมกัน
Return Value
Iterator ชี้ไปที่ Element ที่แทรกใหม่ (หรือ Element เดิมถ้า Key ซ้ำ)
ตัวอย่าง 1: Insert แบบพื้นฐาน
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout << "TP Map is : \nMAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.begin(); i != TP_Map.end(); i++)
cout << i->first << "\t" << i->second << endl;
return 0;
}
ผลลัพธ์
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70
ตัวอย่าง 2: Insert ด้วย Hint Iterator
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
auto it = TP_Map.find(4); // หาตำแหน่ง key 4
TP_Map.insert(it, {5, 80}); // แทรก key 5 ใกล้ key 4
cout << "TP Map is : \nMAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.begin(); i != TP_Map.end(); i++)
cout << i->first << "\t" << i->second << endl;
return 0;
}
ผลลัพธ์
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 5 80