使用empty()是判断vector是否为空的最佳方式,因其性能优、通用性强且语义清晰,示例代码展示其用法及避免对空容器访问的未定义行为。

在C++中,检查一个vector是否为空是日常编程中的常见操作。最推荐、最安全的方式是使用empty()成员函数。
使用 empty() 函数判断 vector 是否为空
empty() 是 std::vector 提供的成员函数,用于判断容器中是否有元素。它返回一个布尔值:
- 如果 vector 没有元素,返回 true
- 如果有至少一个元素,返回 false
示例代码:
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec;
if (vec.empty()) {
std::cout <h3>为什么不推荐用 size() == 0 判断?</h3>
<p>虽然可以通过 <strong>vec.size() == 0</strong> 来判断 vector 是否为空,但不如 <strong>empty()</strong> 推荐,原因如下:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<ul>
<li>
<strong>性能更优</strong>:empty() 的时间复杂度是 O(1),且专为判空设计。对于某些<a style="color:#f60; text-decoration:underline;" title="标准库" href="https://m.php.cn/zt/74427.html" target="_blank">标准库</a>实现,size() 可能需要更多计算(尽管 vector 的 size() 通常也是 O(1))</li>
<li>
<strong>通用性更强</strong>:empty() 可用于所有标准容器(如 list、deque、set 等),而 size() 在某些容器(如 std::forward_list)上可能不是常量时间操作</li>
<li>
<strong>语义清晰</strong>:empty() 更明确表达“判空”意图,提高<a style="color:#f60; text-decoration:underline;" title="代码可读性" href="https://m.php.cn/zt/55554.html" target="_blank">代码可读性</a>
</li>
</ul>
<h3>empty() 的适用场景</h3>
<p>empty() 不仅适用于空 vector 的初始化判断,也常用于:</p>
<ul>
<li>循环遍历前的安全检查</li>
<li>函数返回 vector 后的结果处理</li>
<li>防止对空容器进行 front()/back() 调用导致未定义行为</li>
</ul>
<p>例如:</p>
<pre class="brush:php;toolbar:false;">if (!vec.empty()) {
int first = vec.front(); // 安全访问
}
基本上就这些。使用 empty() 是 C++ 中判断 vector 是否为空的最佳实践,简洁、高效、安全。不复杂但容易忽略。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










