บทความนี้จะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::count() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็นคอนเทนเนอร์แบบ associative ที่จัดเก็บข้อมูลเป็นคู่คีย์-ค่า (key-value pairs) โดยข้อมูลจะถูกจัดเรียงอัตโนมัติตามคีย์ คีย์แต่ละตัวมีค่าเป็นเอกลักษณ์ (unique) และใช้สำหรับเข้าถึงค่าที่เกี่ยวข้อง
map::count() คืออะไร?
map::count() เป็นฟังก์ชันภายใต้เฮดเดอร์ <map> ใช้สำหรับนับจำนวนองค์ประกอบที่มีคีย์เฉพาะ เนื่องจาก map ไม่อนุญาตให้มีคีย์ซ้ำ ฟังก์ชันนี้จึงส่งคืนได้แค่ 2 ค่า:
- 1 – หากคีย์มีอยู่ในคอนเทนเนอร์
- 0 – หากคีย์ไม่มีอยู่ในคอนเทนเนอร์
ไวยากรณ์ (Syntax)
map_name.count(key);
พารามิเตอร์
key – คีย์ที่ต้องการตรวจสอบในคอนเทนเนอร์
ค่าที่ส่งคืน
ส่งคืนค่าบูลีน (0 หรือ 1) แสดงว่าคีย์มีอยู่หรือไม่
ตัวอย่าง Input/Output
Input (key, Element):
(2,70), (3,30), (4,90), (5,100)
Output:
Key 5 is present. Key 6 is not present.
แนวทางการใช้งาน
- สร้างและกำหนดค่าเริ่มต้นให้ map
- แทรกข้อมูลพร้อมคีย์ด้วย
insert()หรือoperator[] - ตรวจสอบคีย์ที่ต้องการด้วย
count()
ตัวอย่างโค้ดที่ 1: ตรวจสอบคีย์แบบ int
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> mp;
mp.insert({1, 40});
mp.insert({3, 20});
mp.insert({2, 30});
mp.insert({5, 10});
mp.insert({4, 50});
if (mp.count(1))
cout << "The Key 1 is present\n";
else
cout << "The Key 1 is not present\n";
if (mp.count(7))
cout << "The Key 7 is Present\n";
else
cout << "The Key 7 is not Present\n";
return 0;
}
ผลลัพธ์
The Key 1 is present The Key 7 is not present
ตัวอย่างโค้ดที่ 2: ตรวจสอบคีย์แบบ char ในลูป
#include <iostream>
#include <map>
using namespace std;
int main() {
map<char, int> mp;
mp['a'] = 2;
mp['c'] = 3;
mp['e'] = 1;
for (char i = 'a'; i < 'f'; i++) {
cout << i;
if (mp.count(i) > 0)
cout << " is an element of mp.\n";
else
cout << " is not an element of mp.\n";
}
return 0;
}
ผลลัพธ์
a is an element of mp. b is not an element of mp. c is an element of mp. d is not an element of mp. e is an element of mp. f is not an element of mp.
หมายเหตุเพิ่มเติม
count()มีความซับซ้อนด้านเวลา O(log n)- สำหรับ multimap (ที่อนุญาตคีย์ซ้ำ)
count()จะส่งคืนจำนวนคีย์ที่ซ้ำกันจริง - วิธีทางเลือก: ใช้
find() != map.end()ซึ่งมีประสิทธิภาพเท่ากันแต่คืนค่า iterator แทน