Empty() and Size() functions in Vectors of C++

 Empty function is used to check if the vector is empty or not while size function is used to get the size of  the vector. Although these functions are compared, but it seems quite hogwash to me, how can we compare two completely different functions, but still...any port in a storm, so basically, empty function is preferred over size function the reasons being:- 

1) Empty function uses comparison operators which are convenient to use.

2) Empty function has a constant time complexity, while size function in some cases has the time complexity of O(n), although this is stupidity to compare an iterating function with a function which just has to check if the vector is empty or not.

One precaution to be taken while using size function is that it returns value of type size_t which is in alias to unsigned long int, so what happens is suppose we do something like vect.size-1 somewhere in the code, then it will return a very big value resulting in a segmentation fault error. To resolve this problem we should always use int typecasting when using size function.

Enough for today, peace out, Get outta here!

Comments

Popular Posts