Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a vector is empty

Tags:

c++

stl

vector

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?

like image 200
Prasoon Saurav Avatar asked Oct 05 '10 11:10

Prasoon Saurav


People also ask

How do you check a vector is empty or not in R?

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 .

What is the size of an empty vector in C++?

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.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Can you have an empty vector C++?

To create an empty vector in C++, just declare the vector with the type and vector name.


1 Answers

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

like image 176
sbi Avatar answered Sep 22 '22 02:09

sbi