隊列是什麼

隊列是一種先進先出(First In First Out)的線性數據結構,類似於現實生活中的排隊場景。新元素總是被添加到隊列的末尾,而從隊列中移除元素時總是從最前面開始。

定義隊列

cpp
// 基本聲明方式
queue<int> q1;                    // 存儲整數的隊列
queue<string> q2;                 // 存儲字符串的隊列
queue<double> q3;                 // 存儲浮點數的隊列

// 可以使用其他容器作為底層容器
queue<int, list<int>> q4;         // 使用list作為底層容器

入隊操作-push()

queue<int> q;
q.push(10);    // 隊列: 10
q.push(20);    // 隊列: 10, 20
q.push(30);    // 隊列: 10, 20, 30

出隊操作-pop()

queue<int> q;
q.push(10);
q.push(20);
q.push(30);

q.pop();       // 移除10,隊列: 20, 30
q.pop();       // 移除20,隊列: 30

注意: pop()函數只移除元素,不返回被移除的元素值。

訪問隊首元素 - front()

queue<int> q;
q.push(10);
q.push(20);
q.push(30);

cout << q.front();  // 輸出: 10
q.pop();            // 移除10
cout << q.front();  // 輸出: 20

訪問隊尾元素 - back()

queue<int> q;
q.push(10);
q.push(20);
q.push(30);

cout << q.back();   // 輸出: 30

檢查隊列是否為空 - empty()

queue<int> q;
cout << q.empty();  // 輸出: 1 (true)

q.push(10);
cout << q.empty();  // 輸出: 0 (false)

獲取隊列大小 - size()

queue<int> q;
q.push(10);
q.push(20);
q.push(30);

cout << q.size();   // 輸出: 3

注意事項

空隊列操作:在對空隊列調用front()、back()或pop()時會導致未定義行為

元素訪問:隊列不支持隨機訪問,只能訪問首尾元素

遍歷限制:不能像vector那樣使用迭代器遍歷隊列