std::unordered_multimap empty() 方法
- 自 C++20 起
- 直到 C++20
// Const version only
bool empty() const noexcept;
// Non const version only
[[nodiscard]] bool empty() const noexcept;
// Const version only
bool empty() const noexcept;
检查容器是否没有元素,即 begin() == end()
。
参数
(无)
返回值
如果容器为空,则为 true
,否则为 false
。
复杂度
常数 - O(1)。
为什么是 [[nodiscard]]
?
[[nodiscard]]
属性是一个属性,它会在函数被调用且其结果被丢弃时引发编译器警告。
在 empty
方法上应用 nodiscard 的原因是,程序员可能会将形容词 empty
(意为“这个容器是否为空?”)与动词 empty
(意为“请帮我清空这个容器。”)混淆。
异常
(无)
示例
Main.cpp
#include <unordered_map>
#include <iostream>
#include <utility>
int main()
{
std::unordered_multimap<int, int> numbers;
std::cout << std::boolalpha;
std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\n';
numbers.emplace(42, 13);
numbers.insert(std::make_pair(13317, 123));
std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\n';
}
输出
Initially, numbers.empty(): true
After adding elements, numbers.empty(): false