4

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?

anonymous38653
  • 393
  • 4
  • 16

2 Answers2

6

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;    
    }
  }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    To make this clearer, understand that a "2D array" is simply an "array-of-arrays". – Abion47 May 13 '20 at 01:49
  • 1
    @Remy Lebeau That answered my question. Can you also tell how do I initialize this-> `std::array ,2> myarray{{5,6},{7,8}};` . I'm getting a `too many initializers` error – anonymous38653 May 13 '20 at 02:07
  • 2
    @shoelace [Why can't simple initialize (with braces) 2D std::array?](https://stackoverflow.com/questions/12844475/) – Remy Lebeau May 13 '20 at 02:08
3
#include <iostream>
#include <array>

int main (){

    const size_t m = someInt;//the outer dim
    const size_t n = anotherOne;//the inner one

    std::array<std::array<int, m>, n> myArray;//it's an array containing m arrays
                                              // each one of them has n integers
    for( size_t i{}; i < m; ++i)  
        for (size_t j=0; j < n; j++){
            myarray[ i ] [ j ] = fillIt;    
        }
}

If u want to use an initializer list, you can use it as follows

std::array myArray{std::array{5,6},std::array{7,8}};//c++17
std::array<std::array<int, 2> > myArray{std::array<int, 2>{5,6},std::array<int, 2>{7,8}};

Note that the last initialization initializes the array with two temporary arrays each one of them has 2 int elements

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • is there a way to avoid typing `std::array` for all the inner arrays in the initializer list? – kwsp Nov 26 '22 at 20:42