Multimap ใน C++ STL คืออะไร?
Multimap เป็น associative container ที่คล้ายกับ map แต่อนุญาตให้มีหลายค่าผูกกับคีย์เดียวกันได้ ข้อมูลจัดเรียงอัตโนมัติตามคีย์
ฟังก์ชัน multimap::size() คืออะไร?
ฟังก์ชัน multimap::size() ประกาศอยู่ใน header <map> ใช้ตรวจสอบขนาดของ multimap container คืนค่าจำนวนองค์ประกอบทั้งหมดใน container
รูปแบบไวยากรณ์ (Syntax)
map_name.size();
พารามิเตอร์
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
ค่าที่ส่งคืน (Return Value)
คืนค่าจำนวนองค์ประกอบใน container (size_type) หาก container ว่างจะคืนค่า 0
ตัวอย่างการใช้งาน
#include <iostream>
#include <map>
using namespace std;
int main() {
multimap<int, int> mul_1;
multimap<int, int> mul_2;
// แทรกข้อมูลเข้า multimap1
mul_1.insert({1, 10});
mul_1.insert({2, 20});
mul_1.insert({3, 30});
mul_1.insert({4, 40});
mul_1.insert({5, 50});
// ตรวจสอบจำนวนองค์ประกอบ
cout << "Total number of elements in multimap1 are: " << mul_1.size();
cout << "\nElements in multimap1 are: " << "\n";
for (auto i = mul_1.begin(); i != mul_1.end(); i++) {
cout << (*i).first << " " << (*i).second << "\n";
}
// multimap2 ว่างเปล่า
cout << "\nSize of empty multimap2: " << mul_2.size();
return 0;
}
ผลลัพธ์
Total number of elements in multimap1 are: 5 Elements in multimap1 are: 1 10 2 20 3 30 4 40 5 50 Size of empty multimap2: 0
การใช้งานร่วมกับฟังก์ชันอื่นๆ
// ตรวจสอบก่อน insert
if (mul.size() < max_allowed) {
mul.insert({key, value});
}
// ใช้ใน loop condition
while (!mul.empty() && mul.size() > threshold) {
// process...
}
สรุป
size() เป็นฟังก์ชันพื้นฐานที่ใช้บ่อยที่สุดสำหรับตรวจสอบจำนวนข้อมูลใน multimap มี time complexity เป็น O(1) ทำให้ใช้งานได้อย่างมีประสิทธิภาพในทุกสถานการณ์