C++ Queue::pop() 函式



C++ 的 std::queue::pop() 函式用於移除佇列的第一個元素。佇列遵循先進先出 (FIFO) 原則,這意味著新增的第一個元素將是第一個被移除的元素。這會使容器大小減一,但不會返回已移除的元素。當嘗試在空佇列上呼叫此函式時,會導致未定義的行為。此函式的時間複雜度為常數 O(1)。

此函式與 front() 函式結合使用,以訪問第一個元素,然後透過呼叫 pop() 函式將其移除。

語法

以下是 std::queue::pop() 函式的語法。

void pop();

引數

它不接受任何引數。

返回值

此函式不返回任何值。

示例

讓我們來看下面的示例,我們將演示 pop() 函式的基本用法。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> x;
    x.push(11);
    x.push(222);
    x.push(3333);
    std::cout << "Before Pop Front Element:" << x.front() << std::endl;
    x.pop();
    std::cout << "After Pop Front Element:" << x.front() << std::endl;
    return 0;
}

輸出

以下是上述程式碼的輸出:

Before Pop Front Element:11
After Pop Front Element:222

示例

考慮下面的示例,我們將使用迴圈彈出並列印每個元素,直到佇列為空。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    for (int x = 1; x <= 4; ++x) {
        a.push(x * 2);
    }
    while (!a.empty()) {
        std::cout << "Popping Element: " << a.front() << std::endl;
        a.pop();
    }
    return 0;
}

輸出

上述程式碼的輸出如下:

Popping Element: 2
Popping Element: 4
Popping Element: 6
Popping Element: 8

示例

在下面的示例中,我們將使用 pop() 函式後檢索佇列的大小。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(1);
    a.push(2);
    a.pop();
    std::cout << "Size of the queue after popping:" << a.size() << std::endl;
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Size of the queue after popping:1

示例

下面的示例將處理佇列,直到滿足條件。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    for (int x = 1; x <= 5; ++x) {
        a.push(x);
    }
    while (!a.empty() && a.front() != 3) {
        std::cout << "Popping Element:" << a.front() << std::endl;
        a.pop();
    }
    return 0;
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Popping Element:1
Popping Element:2
queue.htm
廣告