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

deque::shrink_to_fit() ใน C++ STL


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

Deque คืออะไร?

Deque (Double Ended Queue) เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ที่ทั้งสองปลาย โครงสร้าง queue ทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ปลาย (END) และลบข้อมูลจากหน้า (FRONT) เท่านั้น ส่วน Deque อนุญาตให้แทรกและลบข้อมูลได้ที่ทั้งสองปลาย

deque::shrink_to_fit() คืออะไร?

deque::shrink_to_fit() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <deque> ฟังก์ชันนี้ใช้ ลดความจุ (capacity) ของ deque container ให้เท่ากับขนาด (size) ปัจจุบัน และนำองค์ประกอบที่เกินขนาดที่กำหนดออก ฟังก์ชันนี้มีประโยชน์เมื่อมีปัญหาเรื่องขนาด หรือ container เกินขนาดที่ระบุ

ไวยากรณ์ (Syntax)

mydeque.shrink_to_fit();

พารามิเตอร์ (Parameters)

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

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

ฟังก์ชันนี้ไม่ส่งคืนค่าใดๆ (void)

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

Input: deque<int> mydeque = {10, 20, 30, 40, 0, 0, 0};
mydeque.shrink_to_fit();
Output: Size of the mydeque = 4 (ความจุลดเหลือเท่าขนาดจริง)

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

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

int main() {
    deque<int> Deque(50); // สร้าง deque ขนาด 50
    cout << "Initial size of Deque is : " << Deque.size();
    Deque.resize(40); // ปรับขนาดเหลือ 40
    cout << "\nDeque size after resizing it : " << Deque.size() << endl;
    Deque.shrink_to_fit(); // ลดความจุให้เท่าขนาด
    return 0;
}

ผลลัพธ์ (Output)

Initial size of Deque is : 50
Deque size after resizing it : 40

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

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

int main() {
    deque<int> Deque(10);
    for (int i = 0; i <= 5; i++)
        Deque[i] = i;
    
    cout << "Initial size of Deque is: " << Deque.size();
    cout << "\n Deque elements are: ";
    for (int i = 0; i <= 7; i++)
        cout << Deque[i] << " ";
    
    Deque.resize(10);
    cout << "\n After resizing deque size is : " << Deque.size();
    cout << "\n Deque elements are: ";
    for (int i = 0; i < 10; i++)
        cout << Deque[i] << " ";
    
    Deque.shrink_to_fit();
    return 0;
}

ผลลัพธ์ (Output)

Deque elements are: 0 1 2 3 4 5 0 0
After resizing deque size is : 10
Deque elements are: 0 1 2 3 4 5 0 0 0 0