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

list::empty() และ list::size() ใน C++ STL


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

List ใน STL คืออะไร?

List เป็นคอนเทนเนอร์ที่รองรับการแทรกและลบข้อมูลได้ในเวลาคงที่ (constant time) ที่ตำแหน่งใดก็ได้ในลำดับ List ถูกนำไปใช้งานเป็น doubly linked list ทำให้จัดสรรหน่วยความจำแบบไม่ต่อเนื่องได้ List ให้ประสิทธิภาพการแทรก ดึง และย้ายข้อมูลที่ตำแหน่งใดก็ได้ในคอนเทนเนอร์ดีกว่า array, vector และ deque อย่างไรก็ตาม การเข้าถึงข้อมูลโดยตรง (random access) ใน List ช้ากว่า และ List คล้ายกับ forward_list แต่ forward_list เป็น singly linked list จึงวนลูปได้เฉพาะทิศทางไปข้างหน้าเท่านั้น

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

list::empty() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <list> ฟังก์ชันนี้ใช้สำหรับ ตรวจสอบว่า list container ว่างเปล่าหรือไม่ (ขนาดเป็น 0)

ไวยากรณ์ (Syntax)

listname.empty();

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

ส่งคืน true หาก list ว่าง และ false หากไม่ว่าง

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

Input List: 50 60 80 90
Output: False

Input List: (ว่าง)
Output: True

แนวทางการใช้งาน

  1. ประกาศ List
  2. พิมพ์ List
  3. เรียก empty() function

ตัวอย่างโค้ดเต็ม

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

int main() {
    list<int> list = { 55, 84, 38, 66, 67 };
    
    cout << "List: ";
    for(auto x = list.begin(); x != list.end(); ++x)
        cout << *x << " ";
    
    // เรียก empty()
    if (list.empty()) {
        cout << "\nTrue";
    } else {
        cout << "\nFalse";
    }
    return 0;
}

ผลลัพธ์ (Output)

Input - List: 55 84 38 66 67
Output - False

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

list::size() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <list> ฟังก์ชันนี้ใช้สำหรับ หาขนาดของ list (จำนวนองค์ประกอบใน list)

ไวยากรณ์ (Syntax)

listname.size();

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

ส่งคืนจำนวนองค์ประกอบใน list

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

Input List: 5 6 7 8 9 10
Output: 6

Input List: W O N D E R S
Output: 7

แนวทางการใช้งาน

  1. ประกาศ list
  2. พิมพ์ list
  3. พิมพ์ขนาด list ด้วย size()

ตัวอย่างโค้ดเต็ม

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

int main() {
    list<char> list = { 'M', 'A', 'R', 'C', 'H' };
    
    cout << "List: ";
    for(auto x = list.begin(); x != list.end(); ++x)
        cout << *x << " ";
    
    // ใช้ size() หาจำนวนองค์ประกอบ
    cout << "\nSize of List: " << list.size();
    return 0;
}

ผลลัพธ์ (Output)

Input - List: M A R C H
Output - Size of List: 5