Using a Range for with Multidimensional Arrays

Image

Under the new standard we can simplify the previous loop by using a range for:

size_t cnt = 0;for (auto &row : ia)        // for every element in the outer array    for (auto &col : row) { // for every element in the inner array        col = cnt;          // give this element the next value        ++cnt;              // increment cnt    }

This loop gives the elements of ia the same values as the previous loop, but this time we let the system manage the indices for us. We want to change the value of the elements, so we declare our control variables, row and col, as references (§ 3.2.3, p. 93). The ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.