简体   繁体   中英

is there a difference between vector.size() = 0 and vector.empty()?

I am writing a code in c++ and I want to know when we are calling a vector is there any difference between if the vector.size() = 0 or vecor.empty(); I am confused.

if (Vector.size()>1000)
    if (!Vector.empty())
        std::cout << "I am Here " ;

I wonder to know in order to reach the third line applying the second line makes sense? can we say if the first line is true then we have a vector which is not empty?

There is not difference in observable behavior.

But there can be a difference in the implementation details.

For example if the vector is implemented with a counter, then size() can just return the counter.

empty() can check whether:

vector.counter == 0

And if you call size() == 0 , that will be the same as the empty() implementation. No difference

But in the case of the vector implemented by 2 pointers begin_ptr and end_ptr , then size() has to be computed end_ptr - begin_ptr .

So checking size() == 0 will calculate the size and then compare with 0.

Whereas empty() can just check:

begin_ptr == end_ptr

empty() will be implemented in whatever way the implementer thinks will work the best in the general case.

So I would recommend to call empty() when it is needed.

If you first check if size() > 1000 and then check if it's not empty() . Then logically that's a useless check.

https://en.cppreference.com/w/cpp/container/vector/empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM