Search code examples
c++stdarray

how do I declare a 2d std::array


I want to use a 2d std::array as I've to use bound check at certain point in my program. For 1d array, I would do this:

#include <iostream>
#include <array>
int main (){
  std::array<int,4> myarray;
  for (int i=0; i<10; i++){
     myarray.at(i) = i+1;    
  }
}

How do I do it for a 2d array. Can I make use of auto in it?


Solution

  • std::array is 1-dimensional, there is no such thing as a 2-dimensional std::array. You would simply have to use an inner std::array as the element type of an outer std::array, eg:

    #include <iostream>
    #include <array>
    
    int main(){
      std::array<std::array<int,5>,4> myarray;
      for (int i=0; i<5; i++){
        for (int j=0; j<10; j++){
          myarray[i].at(j) = j+1;    
        }
      }
    }