如何使用'n'维数组声明std :: vector?

时间:2022-09-20 21:29:12

My thoughts are the following:
for e.g. a two-dimensional array:

我的想法如下:例如二维数组:

int a[9][9];
std::vector<int** a> b;

But what if I have

但是,如果我有

/* 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

3 个解决方案

#1


You could also use an alias declaration:

您还可以使用别名声明:

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);
}

#2


Try this:

struct MD_array{ //multidimentional array
   a[3][4][5][6];
};
std::vector<MD_array> b;

Then you can access each array like so:

然后您可以像这样访问每个数组:

b[i].a[x][y][z][w] = value;

#3


You can do this

你可以这样做

int a[3][4][5][6]; 
std::vector<int**** a> b; 

in two ways like this

在这两种方式

int a[3][4][5][6]; 
std::vector<int ( * )[4][5][6]> b; 

b.push_back( a );

and like this

并且喜欢这个

int a[3][4][5][6]; 
std::vector<int ( * )[3][4][5][6]> b; 

b.push_back( &a );

Though it is not clear what you are trying to achieve.:)

虽然目前尚不清楚你想要达到的目的。:)

#1


You could also use an alias declaration:

您还可以使用别名声明:

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);
}

#2


Try this:

struct MD_array{ //multidimentional array
   a[3][4][5][6];
};
std::vector<MD_array> b;

Then you can access each array like so:

然后您可以像这样访问每个数组:

b[i].a[x][y][z][w] = value;

#3


You can do this

你可以这样做

int a[3][4][5][6]; 
std::vector<int**** a> b; 

in two ways like this

在这两种方式

int a[3][4][5][6]; 
std::vector<int ( * )[4][5][6]> b; 

b.push_back( a );

and like this

并且喜欢这个

int a[3][4][5][6]; 
std::vector<int ( * )[3][4][5][6]> b; 

b.push_back( &a );

Though it is not clear what you are trying to achieve.:)

虽然目前尚不清楚你想要达到的目的。:)