ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::cbegin() และ map::cend() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::cbegin() คืออะไร?
map::cbegin() ย่อมาจาก Constant Begin คืน Constant Iterator ชี้ Element แรก ไม่สามารถแก้ไขค่าได้ ใช้สำหรับอ่านอย่างเดียว
Syntax
map_name.cbegin();
Return Value
Constant Iterator ชี้ Element แรก
map::cend() คืออะไร?
map::cend() ย่อมาจาก Constant End คืน Constant Iterator ชี้ Past-the-end ใช้เป็นเงื่อนไขหยุดใน Iteration แบบ Read-only
Syntax
map_name.cend();
Return Value
Constant Iterator ชี้ Past-the-end
ตัวอย่าง
#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});
// ใช้ cbegin() ดึง Element แรก (Read-only)
auto temp = TP_Map.cbegin();
cout << "First element (const): " << temp->first << " -> " << temp->second;
cout << "\nTP Map is (Const Order): \nMAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.cbegin(); i != TP_Map.cend(); i++)
cout << i->first << "\t" << i->second << endl;
return 0;
}
ผลลัพธ์
First element (const): 1 -> 10 TP Map is (Const Order): MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70
ความแตกต่างระหว่าง begin/end และ cbegin/cend
| ฟังก์ชัน | Iterator Type | สามารถแก้ไขค่าได้? |
|---|---|---|
| begin()/end() | Iterator | ได้ |
| cbegin()/cend() | Constant Iterator | ไม่ได้ (Read-only) |
เมื่อไหร่ควรใช้ cbegin/cend?
เมื่อต้องการ Iterate Map เพื่ออ่านค่าเท่านั้น ไม่ต้องการแก้ไข ใช้ Const Iterator เพื่อความปลอดภัยและแสดงเจตนาชัดเจน