How do I find the length of an array?

前端 未结 27 2939
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  时光取名叫无心
    2020-11-21 23:22

    As other's said you can use the sizeof(arr)/sizeof(*arr) but this will give you the wrong answer for pointer types that aren't arrays.

    template
    constexpr size_t size(T (&)[N]) { return N; }
    

    This has the nice property of failing to compile for non array types (visual studio has _countof which does this). The constexpr makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).

    You can also consider using std::array from C++11 which exposes its length with no overhead over a native C array.

    C++17 has std::size() in the header which does the same and works for STL containers too (thanks to @Jon C).

提交回复
热议问题