ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::begin() และ map::end() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::begin() คืออะไร?
map::begin() คืน Iterator ชี้ไปที่ Element แรกของ Map (Key น้อยที่สุด) หาก Map ว่าง Iterator ไม่สามารถ Dereference ได้
Syntax
map_name.begin();
Return Value
Iterator ชี้ Element แรก
map::end() คืออะไร?
map::end() คืน Iterator ชี้ไปที่ตำแหน่ง หลัง Element สุดท้าย (Past-the-end) ใช้เป็นเงื่อนไขหยุดใน Loop หาก Map ว่าง Iterator ไม่สามารถ Dereference ได้
Syntax
map_name.end();
Return Value
Iterator ชี้ Past-the-end
ตัวอย่างการใช้งานร่วมกัน (Iterate ทั้ง Map)
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_1;
TP_1[1] = 10;
TP_1[2] = 20;
TP_1[3] = 30;
TP_1[4] = 40;
cout << "Elements of TP_1:\n";
cout << "\tKEY\tELEMENT\n";
for (auto i = TP_1.begin(); i != TP_1.end(); i++) {
cout << "\t" << i->first << "\t" << i->second << '\n';
}
return 0;
}
ผลลัพธ์
Elements of TP_1: KEY ELEMENT 1 10 2 20 3 30 4 40
สรุป
begin()= เริ่มต้น Mapend()= จบ Map ( Past-the-end )- ใช้คู่กันเพื่อ Iterate ทั้ง Map