跳到主要内容

std::string empty() 方法

// Const version only
[[nodiscard]] constexpr bool empty() const noexcept;

检查容器是否没有元素,即 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:''
本文档源自 此 CppReference 页面。它可能已进行修改以进行改进或满足编辑偏好。点击“编辑此页面”可查看此文档的所有更改。
悬停查看原始许可证。

std::string empty() 方法

// Const version only
[[nodiscard]] constexpr bool empty() const noexcept;

检查容器是否没有元素,即 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:''
本文档源自 此 CppReference 页面。它可能已进行修改以进行改进或满足编辑偏好。点击“编辑此页面”可查看此文档的所有更改。
悬停查看原始许可证。