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

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

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

Multimap เป็น associative container ที่คล้ายกับ map แต่สามารถจัดเก็บหลายค่า (multiple elements) ภายใต้คีย์ (key) เดียวกันได้ ข้อมูลจะถูกจัดเรียงอัตโนมัติตามคีย์

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

ฟังก์ชัน multimap::empty() เป็นฟังก์ชันในตัวของ C++ STL ประกาศอยู่ใน header <map> ใช้ตรวจสอบว่า multimap container ว่างเปล่าหรือไม่

ฟังก์ชันนี้จะตรวจสอบขนาดของ container หากขนาดเป็น 0 จะคืนค่า true หากมีข้อมูลอยู่จะคืนค่า false

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

map_name.empty();

พารามิเตอร์

ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ

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

  • true - หาก multimap ว่างเปล่า (size = 0)
  • false - หาก multimap มีข้อมูลอย่างน้อย 1 รายการ

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

#include <iostream>
#include <map>
using namespace std;

int main() {
    multimap<int, int> mul_1;
    
    // แทรกข้อมูลเข้า multimap
    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});
    
    if (mul_1.empty()) {
        cout << "\nMultimap is empty";
    } else {
        cout << "\nMultimap is not empty";
        cout << "\nElements in multimap1 are: " << "\n";
        for (auto i = mul_1.begin(); i != mul_1.end(); i++) {
            cout << (*i).first << " " << (*i).second << "\n";
        }
    }
    return 0;
}

ผลลัพธ์

Multimap is not empty
Elements in multimap1 are:
1 10
2 20
3 30
4 40
5 50

กรณี Multimap ว่างเปล่า

#include <iostream>
#include <map>
using namespace std;

int main() {
    multimap<int, int> empty_mul;
    
    if (empty_mul.empty()) {
        cout << "Multimap is empty";
    } else {
        cout << "Multimap is not empty";
    }
    return 0;
}

ผลลัพธ์

Multimap is empty

สรุป

ฟังก์ชัน empty() มีประโยชน์สำหรับการตรวจสอบเงื่อนไขก่อนทำการเข้าถึงข้อมูลใน multimap เพื่อป้องกันข้อผิดพลาด เช่นการ dereference iterator ของ container ว่าง ซึ่งจะทำให้เกิด undefined behavior