如何用 'n' 维数组声明 std::vector?
How to declare std::vector with an 'n' dimensional array?
我的想法如下:
例如一个二维数组:
int a[9][9];
std::vector<int** a> b;
但是如果我有呢
/* I know, it is usually a bad practise to have more than 2 dimensional arrays, but it can happen, when you need it */
int a[3][4][5][6];
std::vector<int**** a> b; // ? this just looks bad
你可以做到这一点
int a[3][4][5][6];
std::vector<int**** a> b;
像这样有两种方式
int a[3][4][5][6];
std::vector<int ( * )[4][5][6]> b;
b.push_back( a );
像这样
int a[3][4][5][6];
std::vector<int ( * )[3][4][5][6]> b;
b.push_back( &a );
虽然不清楚您要达到的目标。:)
试试这个:
struct MD_array{ //multidimentional array
a[3][4][5][6];
};
std::vector<MD_array> b;
然后你可以像这样访问每个数组:
b[i].a[x][y][z][w] = value;
您也可以使用别名声明:
template <typename T, size_t I, size_t J, size_t K, size_t N>
using SomeArr = std::array<std::array<std::array<std::array<T, I>, J>, K>, N>;
int main()
{
SomeArr<int,3,4,5,6> arr;
std::vector<SomeArr<int,3,4,5,6>> someVec;
someVec.push_back(arr);
}
我的想法如下:
例如一个二维数组:
int a[9][9];
std::vector<int** a> b;
但是如果我有呢
/* I know, it is usually a bad practise to have more than 2 dimensional arrays, but it can happen, when you need it */
int a[3][4][5][6];
std::vector<int**** a> b; // ? this just looks bad
你可以做到这一点
int a[3][4][5][6];
std::vector<int**** a> b;
像这样有两种方式
int a[3][4][5][6];
std::vector<int ( * )[4][5][6]> b;
b.push_back( a );
像这样
int a[3][4][5][6];
std::vector<int ( * )[3][4][5][6]> b;
b.push_back( &a );
虽然不清楚您要达到的目标。:)
试试这个:
struct MD_array{ //multidimentional array
a[3][4][5][6];
};
std::vector<MD_array> b;
然后你可以像这样访问每个数组:
b[i].a[x][y][z][w] = value;
您也可以使用别名声明:
template <typename T, size_t I, size_t J, size_t K, size_t N>
using SomeArr = std::array<std::array<std::array<std::array<T, I>, J>, K>, N>;
int main()
{
SomeArr<int,3,4,5,6> arr;
std::vector<SomeArr<int,3,4,5,6>> someVec;
someVec.push_back(arr);
}