C++ multimap::empty() 函式



C++ 的std::multimap::empty()函式用於檢查 multimap 是否為空。如果 multimap 為空,則返回布林值 true,否則返回 false。此函式有助於在執行進一步操作之前需要確定 multimap 是否包含任何元素的條件操作。此函式的時間複雜度為常數,即 O(1)。

語法

以下是 std::multimap::empty() 函式的語法。

bool empty() const noexcept;

引數

它不接受任何引數。

返回值

如果 multimap 為空,則此函式返回 true,否則返回 false。

示例

讓我們看下面的例子,我們將演示 empty() 函式的使用。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    if (a.empty()) {
        std::cout << "Multimap is empty." << std::endl;
    } else {
        std::cout << "Multimap is not empty." << std::endl;
    }
    return 0;
}

輸出

以上程式碼的輸出如下:

Multimap is empty.

示例

考慮以下示例,我們將向 multimap 中新增元素並應用 empty() 函式。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert(std::make_pair(1, "Welcome"));
    if (a.empty()) {
        std::cout << "Multimap is empty." << std::endl;
    } else {
        std::cout << "Multimap is not empty." << std::endl;
    }
    return 0;
}

輸出

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

Multimap is not empty.

示例

在下面的示例中,我們將使用 empty() 函式在迴圈中。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "Hi"});
    while (!a.empty()) {
        auto x = a.begin();
        std::cout << "Removing the element: " << x->second << std::endl;
        a.erase(x);
    }
    if (a.empty()) {
        std::cout << "Multimap is empty now." << std::endl;
    }
    return 0;
}

輸出

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

Removing the element: Hi
Multimap is empty now.
multimap.htm
廣告