How to reliably get size of C-style array?

后端 未结 10 1970
广开言路
广开言路 2020-11-29 09:37

How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn\'t work in the foo function

10条回答
  •  死守一世寂寞
    2020-11-29 10:08

    You can either pass the size around, use a sentinel or even better use std::vector. Even though std::vector lacks initializer lists it is still easy to construct a vector with a set of elements (although not quite as nice)

    static const int arr[] = {1,2,3,4,5};
    vector vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
    

    The std::vector class also makes making mistakes far harder, which is worth its weight in gold. Another bonus is that all C++ should be familiar with it and most C++ applications should be using a std::vector rather than a raw C array.

    As a quick note, C++0x adds Initializer lists

    std::vector v = {1, 2, 3, 4};
    

    You can also use Boost.Assign to do the same thing although the syntax is a bit more convoluted.

    std::vector v = boost::assign::list_of(1)(2)(3)(4);
    

    or

    std::vector v;
    v += 1, 2, 3, 4;
    

提交回复
热议问题