C++ multimap::empty() 函数



C++ 的std::multimap::empty()函数用于检查 multimap 是否为空。如果 multimap 为空,则返回布尔值 true,否则返回 false。此函数有助于在执行进一步操作之前需要确定 multimap 是否包含任何元素的条件操作。此函数的时间复杂度为常数,即 O(1)。

语法

以下是 std::multimap::empty() 函数的语法。

bool empty() const noexcept;

参数

它不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果 multimap 为空,则此函数返回 true,否则返回 false。

示例

让我们看下面的例子,我们将演示 empty() 函数的使用。

Open Compiler
#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() 函数。

Open Compiler
#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() 函数在循环中。

Open Compiler
#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
广告