Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน multimap::count() ใน C++ STL

Multimap ใน C++ STL คืออะไร?

Multimap เป็น associative container ที่คล้ายกับ map แต่อนุญาตให้มีหลายค่าผูกกับคีย์เดียวกันได้ ข้อมูลจัดเรียงอัตโนมัติตามคีย์

ฟังก์ชัน multimap::count() คืออะไร?

ฟังก์ชัน multimap::count() ประกาศอยู่ใน header <map> ใช้นับจำนวนองค์ประกอบที่มีคีย์เฉพาะใน multimap เนื่องจาก multimap อนุญาตให้มีหลายค่าต่อคีย์เดียวกัน ฟังก์ชันนี้จึงคืนค่าจำนวนที่มากกว่า 1 ได้

หากคีย์ไม่มีอยู่ใน container จะคืนค่า 0

รูปแบบไวยากรณ์ (Syntax)

multimap_name.count(key_type& key);

พารามิเตอร์

  • key - คีย์ที่ต้องการค้นหาและนับจำนวนองค์ประกอบ

ค่าที่ส่งคืน (Return Value)

คืนค่าจำนวนเต็ม (integer) คือจำนวนองค์ประกอบที่มีคีย์ตรงกับที่ระบุ

ตัวอย่างการใช้งาน

#include <bits/stdc++.h>
using namespace std;

int main() {
    // สร้าง container
    multimap<int, int> mul;
    
    // แทรกข้อมูลด้วย emplace_hint
    mul.emplace_hint(mul.begin(), 1, 10);
    mul.emplace_hint(mul.begin(), 2, 20);
    mul.emplace_hint(mul.begin(), 2, 30);
    mul.emplace_hint(mul.begin(), 1, 40);
    mul.emplace_hint(mul.begin(), 1, 50);
    mul.emplace_hint(mul.begin(), 5, 60);
    
    cout << "\nElements in multimap is: \n";
    cout << "KEY\tELEMENT\n";
    for (auto i = mul.begin(); i != mul.end(); i++) {
        cout << i->first << "\t" << i->second << endl;
    }
    
    cout << "Key 1 appears " << mul.count(1) << " times in the multimap\n";
    cout << "Key 2 appears " << mul.count(2) << " times in the multimap\n";
    
    return 0;
}

ผลลัพธ์

Elements in multimap is:
KEY	ELEMENT
1	50
1	40
1	10
2	30
2	20
5	60
Key 1 appears 3 times in the multimap
Key 2 appears 2 times in the multimap

การประยุกต์ใช้

// ตรวจสอบว่าคีย์มีอยู่หรือไม่ (เร็วกว่า find() สำหรับ multimap)
if (mul.count(key) > 0) {
    // คีย์มีอยู่
}

// นับจำนวนคีย์ที่ซ้ำ
size_t duplicates = mul.count(key) - 1; // ลบ 1 ออก เพราะคีย์ตัวแรกไม่ถือว่า duplicate

สรุป

count() เป็นฟังก์ชันที่สำคัญเฉพาะของ multimap (และ multiset) เนื่องจาก map ธรรมดาจะคืนค่าได้แค่ 0 หรือ 1 เท่านั้น มี time complexity เป็น O(log n + count) โดย n คือขนาด container