jeudi 24 août 2017

Multidimensional Array indexed by integer array

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

        return;
    }
};

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.

Aucun commentaire:

Enregistrer un commentaire