[Solved] What is the most efficient way to check if a C++ container is empty? [closed]


All three options to check for empty container are more or less equivalent. Using empty() shows (as denoted in the comments already) most obviously your intention and as a little bonus, it is even the shortest one to write (that’s for the lazy ones like me…).

How it is implemented? Vendor specific, probably inlined. Option 1 being used for is not unlikely, but not guaranteed.

Classes are more or less a collection of data of whatever appropriate type. Their internal structure must be known at compile time and thus must be always fix *) – and so, in consequence is their size (must be…).

sizeof(c) will return this fixed size, even for containers, no matter how many elements you have placed in there, and this is why sizeof(c) is wrong (actually, it can never get 0, as mentioned by NathanOliver in his answer, but even if it could, it would be constantly 0 then even if the container was not empty).

To illustrate sizeof: Lets look at some standard containers (I’ll leave out the public interface, just concentrate on the data members):

template <typename T>
vector
{
    size_t capacity;
    size_t size;
    T* data;
};

This is roughly all a vector needs. The data contained is stored in some array allocated somewhere on the heap, the only thing that is part of the vector class is the pointer to. sizeof such a vector is likely to be 32 (assuming size_t and pointers being 8 bytes large, as on modern 64 bit hardware, so you get 24 bytes for the members and another 8 for the pointer to the vtable, provided this vector class having virtual members) — constantly.

template<typename T>
class list
{
    class Node
    {
       Node* next;
       Node* previous;
       T data;
    };
    Node* head;
    Node* tail;
};

Again – two pointers internally only, content is allocated inside the nodes somewhere on the heap. head and/or tail might be some dummy nodes for easier use within begin() and end(), but if so, that’s an implementation detail… sizeof(list) would then most likely be 24 — constantly.

*)
“always fix” – during compile time and during runtime of your compiled program; sizes can vary if you compile for different machines (e. g. the vector and list above might have sizes of 16 and 12 if compiled for older 32 bit hardware). Sizes can even vary from one compilation to the other one e. g. due to changed compiler flags (e. g. changing default alignment, …). But during compilation and once compiled, sizeof is fix.

solved What is the most efficient way to check if a C++ container is empty? [closed]