运行时 C++ N 个嵌套向量 [英] C++ N nested vectors at runtime
问题描述
在 C++ 中(有或没有 boost),如何创建 N 维向量,其中 N 在运行时确定?
In C++ (with or without boost), how can I create an N dimensional vectors where N is determined at runtime?
大致如下:
PROCEDURE buildNVectors(int n)
std::vector < n dimensional std::vector > *structure = new std::vector< n dimensional std::vector >()
END
如果传递 1,将分配一个向量.如果传递 2,将分配一个 2d 嵌套矩阵.如果传递 3,则分配一个 3d 立方体.等
If passed 1, a vector would be allocated. If passed 2, a 2d nested matrix would be allocated. If passed 3, a 3d cube is allocated. etc.
推荐答案
很遗憾,您将无法执行此操作.std::vector
是模板类型,因此在编译时必须知道它的类型.由于它的类型用于确定它具有哪些维度,因此您只能在编译时进行设置.
Unfortunately you will not be able to do this. A std::vector
is a template type and as such it's type must be known at compile time. Since it's type is used to determine what dimensions it has you can only set that at compile time.
好消息是您可以创建自己的类,使用单维向量作为数据存储,然后您可以使用数学假装它具有额外的维度.但是,这确实使访问向量变得棘手.由于您不知道向量有多少维,因此您需要一种方法来索引具有任意数量元素的容器.您可以做的是使用 std::intializer_list
重载函数调用运算符运算符,这将允许您使用诸如
The good news is you can make your own class that uses a single dimension vector as the data storage and then you can fake that it has extra dimensions using math. This does make it tricky to access the vector though. Since you will not know how many dimensions the vector has you need to have a way to index into the container with an arbitrary number of elements. What you could do is overload the function call operator operator with a std::intializer_list
which would allow you to index into it with something like
my_fancy_dynamic_dimension_vector({x,y,z,a,b,c});
你可以拥有的真正粗略的草图
A real rough sketch of what you could have would be
class dynmic_vector
{
std::vector<int> data;
int multiply(std::initializer_list<int> dims)
{
int sum = 1;
for (auto e : dims)
sum *= e;
return sum;
}
public:
dynmic_vector(std::initializer_list<int> dims) : data(multiply(dims)) {}
int & operator()(std::initializer_list<int> indexs)
{
// code here to translate the values in indexes into a 1d position
}
};
或者更好的是,只需使用 boost::multi_array
Or better yet, just use a boost::multi_array
这篇关于运行时 C++ N 个嵌套向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!