std::string_view empty() 方法
- 自 C++20 起
- 自 C++17 起
// Const version only
[[nodiscard]] constexpr bool empty() const noexcept;
// Const version only
constexpr bool empty() const noexcept;
检查容器是否没有元素,即 begin() == end()
。
参数
(无)
返回值
如果容器为空,则为 true
,否则为 false
。
复杂度
常数 - O(1)。
为什么是 [[nodiscard]]
?
[[nodiscard]]
属性是一个属性,它会在函数被调用且其结果被丢弃时引发编译器警告。
该属性仅应用于 empty
方法的原因是,程序员很可能会混淆形容词 empty
(表示 - 此容器是否为空?)和动词 empty
(表示 - 请为我清空此容器。)。
示例
Main.cpp
#include <string_view>
#include <iostream>
void check_string(std::string_view ref)
{
// Print a string surrounded by single quotes, its length
// and whether it is considered empty.
std::cout << std::boolalpha
<< "'" << ref << "' has " << ref.size()
<< " character(s); emptiness: " << ref.empty() << '\n';
}
int main(int argc, char **argv)
{
// An empty string
check_string("");
// Almost always not empty: argv[0]
if (argc > 0)
check_string(argv[0]);
}
可能输出
'' has 0 character(s); emptiness: true
'./a.out' has 7 character(s); emptiness: false