Range-based for loop on a dynamic array?

后端 未结 6 1068
暖寄归人
暖寄归人 2020-11-29 07:32

There is a range-based for loop with the syntax:

for(auto& i : array)

It works with constant arrays but not with pointer based dynamic

6条回答
  •  清歌不尽
    2020-11-29 07:52

    You can't use range-for-loop with dynamically allocated arrays, since compiler can't deduce begin and end of this array. You should always use containers instead of it, for example std::vector.

    std::vector v(size);
    for(const auto& elem: v)
        // do something
    

提交回复
热议问题