std::begin and std::end not working with pointers and reference why?

后端 未结 1 1572
野趣味
野趣味 2020-12-16 04:00

Why std::begin() and std::end() works with array but not pointer[which is almost array] and reference of array [which is alias of original

相关标签:
1条回答
  • 2020-12-16 04:53

    Given just a pointer to the start of an array, there's no way to determine the size of the array; so begin and end can't work on pointers to dynamic arrays.

    Use std::vector if you want a dynamic array that knows its size. As a bonus, that will also fix your memory leak.

    The third case fails because, again, you're using (a reference to) a pointer. You can use a reference to the array itself:

    int (&refOfFirst)[3] = first;
    

    or, to avoid having to specify the array size:

    auto & refOfFirst = first;
    

    and begin and end will work on this exactly as they would work on first itself.

    0 讨论(0)
提交回复
热议问题