I am in need of a multidimensional array that can be initialized easily with arbitrary dimensions. I have found this code here, which is beautiful, however poses some difficulties for me. its hard to initialize with arbitrary size and also difficult to access since I have to input each index using a comma to seperate it.
In my application each array 'slot' has the same size. Furthermore it would be easy to work with, if I could index and access everything using an array, instead of having to input every index seperated by a comma. So I wrote the following code which provides something like that, however feels very heavy due to only using one large array. I am basically shifting the 'multidimensional' array layers into one huge array... abusing high valued indices. Is there a way to approve apon the code, making it faster, and using less memory and high value calculations?
#include <iostream>
#include <cmath>
#include <array>
using namespace std;
template <class T, size_t depth, size_t each_size>
class MultiArray
{
array<T, static_cast<size_t>( pow(each_size, depth) )> multiArray;
public:
MultiArray()
{ ; }
void put(array<size_t, depth> indices, T thing_to_put)
{
size_t index = 0;
int dimension_counter = 0;
for (const size_t& i : indices)
{
index += i * nearbyint(pow(each_size, dimension_counter));
dimension_counter++;
}
this->multiArray[index] = thing_to_put;
}
void get(array<size_t, depth> indices, T &thing_to_get)
{
size_t index = 0;
int dimension_counter = 0;
for (const size_t& i : indices)
{
index += i * nearbyint(pow(each_size, dimension_counter));
dimension_counter++;
}
thing_to_get = this->multiArray[index];
}
};
if you would like you can find a slightly longer version of the code above with some debugging, simple testing and very basic error handling here.
EDIT: I would like to find a very fast and efficiant way to do things! I would be happy about input on how to get a fast multidimensional array class :) Thank you all for your help!!!