C++ priority_queue::size() 函式



C++ 的std::priority_queue::size()函式用於確定當前儲存在優先順序佇列中的元素數量。它是一個成員函式,返回一個表示佇列大小的值。size() 函式對於遍歷佇列或依賴於元素數量的條件至關重要。此函式的時間複雜度為常數 O(1)。

語法

以下是 std::priority_queue::size() 函式的語法。

size_type size() const;

引數

此函式不接受任何引數。

返回值

此函式返回優先順序佇列中存在的元素總數。

示例

讓我們看下面的例子,我們將檢查優先順序佇列是否為空。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    if (a.size() == 0) {
        std::cout << "Priority_queue is empty.";
    } else {
        std::cout << "Priority_queue is not empty.";
    }
    return 0;
}

輸出

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

Priority_queue is empty.

示例

考慮下面的例子,我們將使用 size() 來限制優先順序佇列中的元素數量。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    a.push(1);
    a.push(333);
    a.push(22);
    int limit = 2;
    for (int x = 0; x < std::min(a.size(), static_cast<size_t>(limit)); ++x) {
        std::cout << a.top() << " ";
        a.pop();
    }
    return 0;
}

輸出

上述程式碼的輸出如下 -

333 22

示例

在下面的示例中,我們將列印在迴圈中插入每個元素後優先順序佇列的大小。

#include <iostream>
#include <queue>
int main()
{
    std::priority_queue<int> a;
    for (int x = 0; x < 3; ++x) {
        a.push(x * 2);
        std::cout << "Size after inserting " << (x + 1) << " elements: " << a.size() << std::endl;
    }
    return 0;
}

輸出

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

Size after inserting 1 elements: 1
Size after inserting 2 elements: 2
Size after inserting 3 elements: 3

示例

以下示例演示了彈出元素後優先順序佇列的大小如何變化。

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

輸出

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

Size of the priority_queue before popping : 3
Size of the priority_queue after popping : 2
priority_queue.htm
廣告

© . All rights reserved.