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

queue::push() และ queue::pop() ใน C++ STL


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

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

Queue เป็นโครงสร้างข้อมูลหรือลำดับข้อมูลพื้นฐานใน C++ STL ที่จัดการข้อมูลแบบ FIFO (First In First Out) ข้อมูลใน queue จะถูกจัดเก็บอย่างต่อเนื่อง องค์ประกอบจะถูกแทรกที่ปลาย (rear/back) และนำออกจากหน้า (front) C++ STL มี template ของ queue ให้ใช้งานสำเร็จรูปแล้ว

queue::push() คืออะไร?

queue::push() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <queue> ฟังก์ชันนี้ใช้สำหรับ แทรก (push/insert) องค์ประกอบใหม่ ที่ปลายหรือด้านหลัง (back) ของ queue container ฟังก์ชันรับพารามิเตอร์หนึ่งคือองค์ประกอบที่ต้องการแทรก และเพิ่มขนาดของ container ขึ้น 1 ฟังก์ชันนี้จะเรียก push_back() ภายในเพื่อแทรกข้อมูลที่ด้านหลังได้อย่างง่ายดาย

ไวยากรณ์ (Syntax)

myqueue.push(value);

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

รับพารามิเตอร์หนึ่งคือค่าที่ต้องการแทรก (type ต้องตรงกับชนิดข้อมูลใน queue)

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

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

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

Input: queue<int> myqueue = {10, 20, 30, 40};
myqueue.push(23);
Output: Elements in the queue are = 10 20 30 40 23

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

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

int main() {
    queue<int> Queue;
    for(int i = 0; i <= 5; i++) {
        Queue.push(i);
    }
    
    cout << "Elements in queue are : ";
    while (!Queue.empty()) {
        cout << ' ' << Queue.front();
        Queue.pop();
    }
}

ผลลัพธ์ (Output)

Elements in queue are : 0 1 2 3 4 5

queue::pop() คืออะไร?

queue::pop() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <queue> ฟังก์ชันนี้ใช้สำหรับ ลบ (pop/delete) องค์ประกอบที่มีอยู่ จากจุดเริ่มต้นหรือหน้า (front) ของ queue container ฟังก์ชันไม่รับพารามิเตอร์ และลบองค์ประกอบจากหน้าของ queue ที่เกี่ยวข้อง ลดขนาดของ queue container ลง 1

ไวยากรณ์ (Syntax)

myqueue.pop();

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

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

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

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

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

Input: queue<int> myqueue = {10, 20, 30, 40};
myqueue.pop();
Output: Elements in the queue are = 20 30 40

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

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

int main() {
    queue<int> Queue;
    for(int i = 0; i <= 5; i++) {
        Queue.push(i);
    }
    for(int i = 0; i < 5; i++) {
        Queue.pop();
    }
    
    cout << "Element left in queue is : ";
    while (!Queue.empty()) {
        cout << ' ' << Queue.front();
        Queue.pop();
    }
}

ผลลัพธ์ (Output)

Element left in queue is : 5