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

โปรแกรม C++ สำหรับการใช้งาน Queue ใน STL

Queue (คิว) เป็นโครงสร้างข้อมูลแบบเส้นตรงที่ปฏิบัติตามลำดับ FIFO (First In First Out) - ตัวที่เข้าก่อนจะออกก่อน

ฟังก์ชันและคำอธิบาย

  • q.size() – คืนขนาดของคิว
  • q.push() – ใช้แทรกองค์ประกอบเข้า คิว (ที่ท้าย)
  • q.pop() – นำค่าออกจาก คิว (จากหน้า)
  • q.front() – คืนองค์ประกอบหน้าสุดของคิว
  • q.back() – คืนองค์ประกอบท้ายสุดของคิว

โค้ดตัวอย่าง (โปรแกรมโต้ตอบแบบเมนู)

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

int main() {
    queue<int> q;
    int c, i;

    while (true) {
        cout << "1.Size of the Queue" << endl;
        cout << "2.Insert Element into the Queue" << endl;
        cout << "3.Delete Element from the Queue" << endl;
        cout << "4.Front Element of the Queue" << endl;
        cout << "5.Last Element of the Queue" << endl;
        cout << "6.Exit" << endl;
        cout << "Enter your Choice: ";
        cin >> c;

        switch(c) {
            case 1:
                cout << "Size of the Queue: " << q.size() << endl;
                break;
            case 2:
                cout << "Enter value to be inserted: ";
                cin >> i;
                q.push(i);
                break;
            case 3:
                if (!q.empty()) {
                    i = q.front();
                    q.pop();
                    cout << "Element " << i << " Deleted" << endl;
                } else {
                    cout << "Queue is Empty" << endl;
                }
                break;
            case 4:
                if (!q.empty())
                    cout << "Front Element of the Queue: " << q.front() << endl;
                else
                    cout << "Queue is Empty" << endl;
                break;
            case 5:
                if (!q.empty())
                    cout << "Back Element of the Queue: " << q.back() << endl;
                else
                    cout << "Queue is Empty" << endl;
                break;
            case 6:
                exit(0);
            default:
                cout << "Wrong Choice" << endl;
        }
    }
    return 0;
}

ตัวอย่างผลลัพธ์

1.Size of the Queue
2.Insert Element into the Queue
3.Delete Element from the Queue
4.Front Element of the Queue
5.Last Element of the Queue
6.Exit
Enter your Choice: 1
Size of the Queue: 0
Enter your Choice: 2
Enter value to be inserted: 1
Enter your Choice: 2
Enter value to be inserted: 2
Enter your Choice: 3
Element 1 Deleted
Enter your Choice: 2
Enter value to be inserted: 4
Enter your Choice: 2
Enter value to be inserted: 7
Enter your Choice: 2
Enter value to be inserted: 6
Enter your Choice: 4
Front Element of the Queue: 2
Enter your Choice: 5
Back Element of the Queue: 6
Enter your Choice: 6
Exit code: 0

ข้อสังเกต: โค้ดต้นฉบับไม่มีการตรวจสอบ empty() ก่อน pop/front/back โค้ดด้านบนเพิ่มการตรวจสอบเพื่อความปลอดภัย