检查向量是否为空 [英] Checking whether a vector is empty
问题描述
假设我有一个 std::vector
说 Vector
现在对向量执行一些操作(插入或删除)后,我想检查向量是否为空,并在此基础上我想执行一些操作.
Now after performing some operations on the vector(either insertion or deletion) I want to check if the vector is empty and on the basis of that I want to perform some operations.
哪种方法更好
方法一
if (Vector.size() == 0){ /* operations */ }
方法二
if (Vector.empty()) { /* operations */ }
1
或 2
哪个更好?
推荐答案
v.size() == 0
说我正在比较大小",但这样做是为了检查容器是否空的.在你知道它做什么之前,有一个小算法需要消化(非常小,因为它只包含一个比较).
OTOH,v.empty()
完全符合它所说的:它检查 v
是否为空.
由于这个原因,我显然更喜欢#2,因为它按照它所说的去做.毕竟,这就是发明 empty()
的原因.
v.size() == 0
says "I'm comparing the size", but does so to check whether the container empty. There's a small algorithm to digest (very small, as it only consists of a comparison) before you know what it does.
OTOH, v.empty()
does exactly what it says: it checks whether v
is empty.
Due to this, I clearly prefer #2, as it does what it says. That's why empty()
was invented, after all.
但也有一个算法原因更喜欢 empty()
:如果有人后来将 std::vector
更改为 std::list
, v.size()
可能有 O(n).(在 C++ 03 中,std::vector
保证为 O(1),但对于 std::list
则不保证.根据 James 对 Prasoon 的答案所有em> C++1x 中的容器.)
But there's also an algorithmic reason to prefer empty()
: If someone later changes std::vector
into a std::list
, v.size()
might have O(n). (In C++ 03 it's guaranteed to be O(1) for std::vector
, but not for std::list
. According to James' comment to Prasoon's answer it will be O(1) for all containers in C++1x.)
这篇关于检查向量是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!