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

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


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::empty() ใน C++ STL

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

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน

map::empty() คืออะไร?

map::empty() เป็นฟังก์ชันใน header <map> ใช้ตรวจสอบว่า Map Container ว่างหรือไม่ คืนค่า true ถ้าขนาดเป็น 0 มิฉะนั้น false

Syntax

map_name.empty();

Parameters

ไม่มีพารามิเตอร์

Return Value

true ถ้า Map ว่าง, false ถ้า Map มีข้อมูล

ตัวอย่าง

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

int main() {
    map<int, int> TP_1;
    TP_1[1] = 10;
    TP_1[2] = 20;
    TP_1[3] = 30;
    TP_1[4] = 40;
    
    if (TP_1.empty()) {
        cout << "Map is NULL";
    } else {
        cout << "Map isn't NULL";
    }
    return 0;
}

ผลลัพธ์

Map isn't NULL

ตัวอย่างเปรียบเทียบ Map ว่างและไม่ว่าง

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

int main() {
    map<int, int> TP_1;
    map<int, int> TP_2; // ว่าง
    
    TP_1[1] = 10;
    TP_1[2] = 20;
    TP_1[3] = 30;
    TP_1[4] = 40;
    
    if (TP_1.empty()) cout << "Map_1 is NULL";
    else cout << "Map_1 isn't NULL";
    
    if (TP_2.empty()) cout << "\nMap_2 is NULL";
    else cout << "\nMap_2 isn't NULL";
    
    return 0;
}

ผลลัพธ์

Map_1 isn't NULL
Map_2 is NULL