问题描述
一个类是否可能有一个成员,它是一个多维数组,其维度和范围直到运行时才知道?
Is it possible for a class to have a member which is a multidimensional array whose dimensions and extents are not known until runtime?
我发现(通过 本指南) 一种创建结构以在编译时使用模板元编程轻松嵌套 std::arrays 的方法:
I have found (via this guide) a way to create a struct to easily nest std::arrays at compile time using template metaprogramming:
#include <array>
/*
this struct allows for the creation of an n-dimensional array type
*/
template <typename T,size_t CurrentDimExtent,size_t... NextDimExtent>
struct MultiDimArray{
public:
//define the type name nestedType to be a recursive template definition.
using nestedType=typename MultiDimArray<T,NextDimExtent...>::type;
using type=std::array<nestedType,CurrentDimExtent>;
};
/*
This struct is the template specialization which handles the base case of the
final dimensional extent
*/
template <typename T,size_t DimExtent>
struct MultiDimArray<T,DimExtent>{
using type=std::array<T,DimExtent>;
};
这在两个方面仍然不能满足我的要求(我知道):
this still falls short of satisfying my requirement in two ways (that I know of):
- 为了声明这种类型的变量(或指向变量的指针),您必须说明维度.
- 这只适用于 DimExtents 是常量表达式(在编译时设置).
为了说明为什么数字 2 是一个明显的问题,这里有一个具有一组维度 (2) 的类,使用 void* 来引用多维数组:
To demonstrate why number 2 is a distinct problem, here is a class with a set number of dimensions (2) using a void* to reference the multidimensional array:
template <typename T>
class TwoDimGrid{
public:
TwoDimGrid(const size_t extent1,const size_t extent2):
_twoDimArray(new MultiDimArray<T,extent1,extent2>);
private:
void* _twoDimArray;
};
这不会编译,因为 extent1 和 extent2 不是常量表达式.
This will not compile as extent1 and extent2 are not constant expressions.
其他注意事项:
- 我想看看是否可以使用 std:array 来完成,而不是使用本机数组或像 std::vector 这样的动态调整大小的容器.
- 请在适当的情况下使用智能指针(我没有使用,因为我不确定如何处理智能空指针).
我掉进了XY 问题的陷阱,X 是这个问题的第一句话和 Y 是如何用 std::array 完成它.因此,我创建了一个 新问题,我把这个留在这里,以防万一有可能解决 Y 问题.
I have fallen into the trap of The XY Problem with X being the first sentence of this question and Y being how to accomplish it with std::array. I therefore created a new question and am leaving this one here in case it's ever possible to solve Y problem.
推荐答案
template <typename T>
class vvc
{
//possible ragged array ..non rigorous approach
//with management memory cost per element
//clearly not as efficient as .... linearized access where access index is
//row size * r + column
//memory management courtesy of vector
public:
std::vector< std::vector<T> > v;
};
int double_vector()
{
int x1 = 5;
int x2 = 3;
std::vector<int> r(x2);
vvc<int> vv;
int k = 0;
for (int i1 = 0; i1 < x1; ++i1)
{
for (int i2 = 0; i2 < x2; ++i2)
{
k += 1;
r[i2] = k;
}
vv.v.push_back(r);
}
//inspect
cout << vv.v[0][0] << " first " << endl;
for (auto const & t1 : vv.v)
{
for (auto const &t2 : t1 )
{
cout << t2 << " ";
}
cout << endl;
}
return 0;
}
这篇关于使用嵌套的 std::array 创建多维数组,直到运行时才知道维度或范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!