在运行时C ++ N个嵌套向量 [英] C++ N nested vectors at runtime

查看:75
本文介绍了在运行时C ++ N个嵌套向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

您可能拥有的真实草图

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

或更妙的是,只需使用

Or better yet, just use a boost::multi_array

这篇关于在运行时C ++ N个嵌套向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆