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

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


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

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

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

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

map::size() เป็นฟังก์ชันใน header <map> ใช้ตรวจสอบขนาดของ Map Container คืนค่าจำนวน Elements ใน Map

Syntax

map_name.size();

Parameters

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

Return Value

จำนวน Elements ใน Map (เป็น size_type ซึ่งเป็น unsigned integer) ถ้า Map ว่าง คืนค่า 0

ตัวอย่าง

#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;
    
    cout << "Size of TP_1 is: " << TP_1.size();
    return 0;
}

ผลลัพธ์

Size of TP_1 is: 4

ตัวอย่างเพิ่มเติม: ใช้ size() ในการคำนวณ

#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;
    
    auto size = TP_1.size();
    auto temp = 1;
    while (size != 0) {
        temp = temp * 10;
        size--;
    }
    cout << "Temp value is: " << temp << endl;
    return 0;
}

ผลลัพธ์

Temp value is: 10000