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
563 views
in Technique[技术] by (71.8m points)

c++ - Setting pointer to arbitrary dimension array?

When I want to initiate a multidimensional array, I usually just use pointers. For example, for two dimensions I use:

double **array

and for three I use:

double ***array

However, I'd like to set a multidimensional array based on a command line argument indicating the dimension. Is there are way to set an array of arbitrary size once you have a variable with the number of dimensions you'd like?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Even though this whole question is an indication of a design flaw, you can (sort of) accomplish this:

template<typename T>
class MultiArray
{
public:
    MultiArray(std::size_t dimen, std::size_t dimen_size) : _dimensions(dimen)
    {
        _data = new T[dimen * dimen_size];
    }

    // implment copy constructor, copy-assignment operator, destructor, and move constructors as well

    T* operator[](int i)
    {
        assert(0 <= i && i < _dimensions); // bounds check for your dimension
        return &_data[i];
    }
private:
    T* _data;
    std::size_t _dimensions;
};

int main()
{
    MultiArray<int> a(5, 2);
    a[4][1] = 3;
    std::cout << a[4][1] << std::endl;
    return 0;
}

If you want it jagged, you would have to do more math and maintenance regarding the bounds for each "dimension".

The problem you run into has making the dimensions mean something for your application. Typically, a multi-dimensional array represents something (e.g. a 2D vector can represent Cartesian space, a 3D or 4D vector can be used for manipulating data for 3D graphics). Beyond the 4th dimension, finding a valid meaning for the array becomes murky and maintaining the logic behind it becomes increasingly complex with each new dimension.


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