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

ฟังก์ชัน deque::resize() ใน C++ STL


งานนี้เป็นการแสดงฟังก์ชันการทำงานของ deque::resize() ใน C++ STL

Deque คืออะไร

Deque หรือ Double Ended Queues เป็นคอนเทนเนอร์ลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ทั้งสองข้าง คิวโครงสร้างข้อมูลทั่วไปอนุญาตให้แทรกข้อมูลเฉพาะที่ท้ายและลบข้อมูลจากหน้าเท่านั้น การเปรียบเทียบกับคิวที่ป้ายรถเมล์ ที่คนสามารถแทรกเข้าคิวได้เฉพาะท้าย และคนหน้าสุดจะออกก่อน ส่วน deque แทรกและลบได้ทั้งสองข้าง

deque::resize() คืออะไร

ฟังก์ชัน deque::resize() ใช้เปลี่ยนขนาดของ deque ถ้าขนาดใหม่มากกว่าขนาดปัจจุบัน องค์ประกอบใหม่จะถูกแทรกที่ท้ายของ deque ถ้าขนาดที่กำหนดน้อยกว่าขนาดปัจจุบัน องค์ประกอบส่วนเกินจะถูกลบ

ไวยากรณ์

deque_name.resize(n)

พารามิเตอร์

n: กำหนดขนาดของ deque

ตัวอย่าง

อินพุต ขนาดปัจจุบัน - 5

Deque - 12 13 14 15 16

เอาต์พุต ขนาดหลัง resize - 7

New Deque - 11 12 13 14 15 16 17

อินพุต ขนาดปัจจุบัน - 5

Deque - F O R C E

เอาต์พุต ขนาดหลัง resize - 4

New Deque - F O R C

แนวทางการทำงาน

  • ประกาศ deque ก่อน
  • ตรวจสอบขนาดของ deque
  • พิมพ์ deque
  • กำหนดฟังก์ชัน resize()
  • พิมพ์ deque ใหม่หลัง resize

ด้วยแนวทางด้านบน เราสามารถปรับขนาด deque ได้

ตัวอย่าง

// C++ code to demonstrate the working of deque resize() function
#include <iostream>
#include <deque>
using namespace std;

int main() {
    // initializing the deque
    deque<int> dq = { 85, 87, 88, 89, 90 };
    cout << "Size of deque: " << dq.size() << "\n";
    // print the deque
    cout << "Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    // defining the resize() function
    dq.resize(7);
    // printing deque after resize
    cout << "\nDeque after resize: " << dq.size() << "\n";
    cout << "New Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Size of deque: 5
Deque: 85 87 88 89 90
Deque after resize: 7
New Deque: 85 87 88 89 90 0 0

ตัวอย่างที่ 2

// C++ code to demonstrate the working of deque resize() function
#include <iostream>
#include <deque>
using namespace std;

int main() {
    // initializing deque
    deque<int> dq = { 14, 15, 16, 17, 18, 19, 20 };
    cout << "Size of deque: " << dq.size() << "\n";
    // print the deque
    cout << "Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    // defining the resize() function
    dq.resize(5);
    // printing deque after resize
    cout << "\nDeque after resize: " << dq.size() << "\n";
    cout << "New Deque: ";
    for(auto x = dq.begin(); x != dq.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Size of deque: 7
Deque: 14 15 16 17 18 19 20
Deque after resize: 5
New Deque: 14 15 16 17 18