Search code examples
c++stdarray

what is the point of std::array function?


In the C++ array implementation, an empty method is provided. However as the implementation suggests:

constexpr bool
empty() const noexcept { return size() == 0; }

This only returns true if the size of the array is 0 so what is the point of it?

the typical use case for std::array is something like this: std::array<type,size> a = {init here maybe}; or a[index] = value; afterwards.

Is there any use case where you would declare a zero length array or get it from somewhere that an empty check would be useful?


Solution

  • is there any use case where you would declare a zero length array or get it from somewhere that an empty check would be useful?

    If you're using a template for the size of the array. for example

    #include <array>
    
    template <std::size_t s>
    void function(std::array<int, s> const& array) {
        if (!array.empty()) {
            // other array operations ...
        }
    }
    
    int main() {
        auto empty_array = std::array<int, 0>{};
        function(empty_array);
        auto array = std::array<int, 9>{};
        function(array);
    }
    

    in this case, in function accepts arrays of different sizes so we cant be 100% sure its not empty.

    edit:

    additionally, the size and empty members are useful in generic code (e.g. a function that works on any container) when we have no other way to get the size (in my first example you technically can get the size from s). for example

    template <class Container>
    void function(Container const& array) {
        if (!array.empty()) {
            // other container operations ...
        }
    }