std::string empty() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// Const version only
[[nodiscard]] constexpr bool empty() const noexcept;
// Const version only
bool empty() const noexcept;
// Const version only
bool empty() const;
检查容器是否没有元素,即 begin() == end()
。
参数
(无)
返回值
如果容器为空,则为 true
,否则为 false
。
复杂度
常数 - O(1)。
为什么是 [[nodiscard]]
?
[[nodiscard]]
属性是一个属性,它会在函数被调用且其结果被丢弃时引发编译器警告。
将该属性仅应用于 empty
方法的原因是,程序员很可能会将形容词 empty
(表示 - 此容器是否为空?)与动词 empty
(表示 - 请为我清空此容器。)混淆。
示例
Main.cpp
#include <iostream>
#include <string>
int main()
{
std::string s;
std::boolalpha(std::cout);
std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n";
s = "Exemplar";
std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n";
s = "";
std::cout << "s.empty():" << s.empty() << "\t s:'" << s << "'\n";
}
输出
s.empty():true s:''
s.empty():false s:'Exemplar'
s.empty():true s:''