问题
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?
回答1:
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;
}
}
}
回答2:
#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
来源:https://stackoverflow.com/questions/61764983/how-do-i-declare-a-2d-stdarray