Element count of an array in C++

前端 未结 11 1747
[愿得一人]
[愿得一人] 2020-12-05 10:38

Let\'s say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

I can

11条回答
  •  臣服心动
    2020-12-05 10:40

    First off, you can circumvent that problem by using std::vector instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:

    • normal pointers
    • a collection of boost::shared_ptr
    • a Boost.Pointer Container

提交回复
热议问题