Range-based for loop on a dynamic array?

后端 未结 6 1073
暖寄归人
暖寄归人 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:51

    C++20 will (presumably) add std::span, which allows looping like this:

    #include 
    #include 
    
    int main () {
        auto p = new int[5];
        for (auto &v : std::span(p, 5)) {
            v = 1;
        }
        for (auto v : std::span(p, 5)) {
            std::cout << v << '\n';
        }
        delete[] p;
    }
    

    This is supported by current compilers, e.g. gcc 10.1 and clang 7.0.0 and later. (Live)

    Of course, if you have the choice, it is preferable to use std::vector over C-style arrays from the get-go.

提交回复
热议问题