Search code examples
c++stdarray

Range based for with multi-dimensional std::array


Tried looking around for this but only found examples using built in array not std::array obj.

// array arr of size 5
array< array<int, 10>, 10> arr = { 0 };

srand((unsigned)time(0));

// initialize elements
for ()
{
    for()
    {
        item = rand() % 100 + 1;
    }
}

basic example trying to initialize 2D array obj to random values. im not sure what to put between the () of the for loops


Solution

  • #include <array>
    using namespace std;
    
    // array arr of size 5
    array< array<int, 10>, 10> arr;
    
    int main() {
      // initialize elements
      for (auto & outer_array : arr)  
      {
          for(auto & inner_array : outer_array)
          {
    
          }
      }
    }
    

    live: https://godbolt.org/g/6eLgBk