Suppose I have a std::vector
say 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.
Which approach is better
Approach 1
if (Vector.size() == 0){ /* operations */ }
Approach 2
if (Vector.empty()) { /* operations */ }
Which is a better approach, 1
or 2
?
If you check length(vec) , we know the length of our vector is also 0, meaning that our vector, vec , is empty. If you want to create other types of vectors that are not of type logical , you can also read the help file of vector using ? vector .
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.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
To create an empty vector in C++, just declare the vector with the type and vector name.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With