简体   繁体   中英

stack.size() vs stack.empty()

to check whether a stack is empty, we can use if(stack.size()) . Then why do we have stack.empty() .
Is there any condition where these results may differ or any advantage of using one over other.

To some degree it's a style choice .

Personally I think relying on implicit bool conversion should be restricted to things with pointer-like semantics: actual pointers, smart pointers, std::optional come to mind. It is ubiquitous in that context and just feels natural.

In other contexts it feels weird. Communicate your intent as clearly as possible! Again in my opinion if(.stack.empty()) communicates intent a lot more clearly and directly than if(stack.size()) .

However, style is not the whole story. If you use the size style as a general rule it can become a performance problem , because you rely on both size() and empty() to be equally fast.

Imagine a linked list type that does not store its size. Its empty() function is still fast because it amounts to checking a single pointer. But its size() has to traverse the whole list to determine the number of items. That can be a vastly more expensive operation.

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