本文介绍了size()Vs empty()in vector - 为什么空()是首选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调试时,我看到了STL vector :: empty()实现:

While debugging something, I saw the STL vector::empty() implementation:

bool empty() const
    	{return (size() == 0); }

我相信,每当我们探测向量的空白时,总是建议使用空大小()。但看到实施,我想知道,这样做的好处是什么?相反,在调用空的函数调用开销,因为它内部调用size()== 0。

I believe, whenever we are probing the emptiness of vector it is always recommended to use empty over size(). But seeing that implementation, I am wondering, what is the benefit of doing so? Instead, there is a function call overhead in calling empty as it internally calls size()==0.

我认为empty() size()不保证列表中的常量时间。为了验证我的假设,我检查了列表的实现,令人惊讶的是,在列表中也发现了相同的实现。

I thought empty() may be helpful in case of list as size() doesn't guarantees the constant time in list. To verify my assumption, I checked the list implementation and surprisingly, found the same implementation in list as well,

return (size() == 0);

现在我很困惑。如果empty在内部使用size(),那么为什么我们应该更喜欢empty over size()?

I am bit confused now. If empty internally uses size() then why should we prefer empty over size() ?

推荐答案

每次你使用 size()。使用 empty()很方便。这当然是,只要你不切换容器。正如其他人指出的那样,在 empty()中使用 size()然而,标准确认: empty()是所有
标准容器的常量操作。

You would need to write the condition out everytime you use size(). It's convenient to use empty(). This is of course, provided you don't switch containers. As others have pointed out, it is upto the implementation to use size() in empty() or not. However, the standard does gurantee that: empty() is a constant-time operation for allstandard containers.

这篇关于size()Vs empty()in vector - 为什么空()是首选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 08:47