C++ N nested vectors at runtime

不想你离开。 提交于 2019-12-31 02:15:06

问题


In C++ (with or without boost), how can I create an N dimensional vectors where N is determined at runtime?

Something along the lines of:

PROCEDURE buildNVectors(int n)

std::vector < n dimensional std::vector > *structure = new std::vector< n dimensional std::vector >()

END

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.


回答1:


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.

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

Or better yet, just use a boost::multi_array



来源:https://stackoverflow.com/questions/43358369/c-n-nested-vectors-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!