Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I declare a 2d std::array

Tags:

c++

stdarray

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?

like image 416
anonymous38653 Avatar asked Oct 14 '25 04:10

anonymous38653


2 Answers

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;    
    }
  }
}
like image 122
Remy Lebeau Avatar answered Oct 16 '25 18:10

Remy Lebeau


#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

like image 33
asmmo Avatar answered Oct 16 '25 17:10

asmmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!