Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - C++ N nested vectors at runtime

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...