0

I want to implement a function that gets as a parameter a dimension "n" of an array of integers. This function also gets values "k_1, k_2, ..., k_n" defining the size of the array. Then this function will fill this n-dimensional array.

How do I implement this efficiently with C++?

For example for n = 3 I would use

vector < vector < vector < int > > > array;

But I don't know the dimension at compile time.

2
  • If n is your dimension, k_1...k_n is not nearly enough data. Commented Feb 2, 2011 at 16:17
  • Are n-dimensional arrays part of the problem or the solution? Commented Feb 2, 2011 at 16:17

2 Answers 2

3

Use a one-dimensional array, and fake the other dimensions using multiplication of offsets for indexing, and you can pass the dimension sizes in by vector, i.e.

std::vector<int> create_md_array(const std::vector<int> & dimensions)
{
    int size = std::accumulate(dimensions.begin(), dimensions.end(), 1, std::multiplies<int>());
    return std::vector<int>(size);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice idea. You can then extend std::vector<int> for providing some syntax sugar for getting and setting an element of this array (for example overloading operator())
@Murilo: I would not extend vector. This would be wrapped in a separate class.
I actually implemented a N-dimensional array in cpp. This is what I did.
0

You have a couple of choices. You can implement it yourself, basically multiplying the coordinates by the sizes to linearize the multi-dimensional address, and just have a simple std::vector<whatever> to hold the data.

Alternatively, you could use std::valarray and friends to accomplish the same. It has a set of classes that are specifically intended for the kind of situation you describe -- but they're used so rarely that almost nobody understands them. Writing the code yourself stands a good chance of being easier for most people to read and understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.