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
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.