Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size() Vs empty() in vector - why empty() is preferred?

Tags:

c++

stl

size

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

bool empty() const         {return (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.

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); 

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

like image 235
aJ. Avatar asked Apr 13 '09 06:04

aJ.


People also ask

Is an empty vector size 0?

If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.

How do you know if a vector is empty?

C++ Vector empty() empty() returns true if the vector is empty, or false if the vector is not empty.

How do you return an empty vector in C++?

prefix == prefix) { find =1; return map[i]. sufix; //sufix is a vector from a class called "Pair. h" } } if(find==0) { //return an empty vector. } }

How do I get the size of a vector in C++?

To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.


2 Answers

Because if you switch from std::vector to std::list or other container, it may be different.

For example some implementations of std::list::size take O(n) and not O(1).

like image 71
Artyom Avatar answered Oct 06 '22 00:10

Artyom


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 guarantee that: empty() is a constant-time operation for all standard containers.

like image 20
dirkgently Avatar answered Oct 06 '22 00:10

dirkgently