How to access 1D data (or reshape it) from pointer into something like multidimensional array in C++?

Viewed 42

I have a pointer that points to the beginning of a 1000+ elements array that is initialized as below:

int numElements = 1200;
auto data = std::unique_ptr<float>{new float[numElements]};

Now I want to 'reshape' it into something like a (20,30,20) tensor, so I can access it the way I want (I can still read while it's 1-D as well but it feels weird). I want to access like this:

data[1][10][12] = 1337.0f;

Is there an efficient way of doing this (fast and short code)?

1 Answers

In the meantime, this is how I do it...

#include <iostream>
using std::cout;
using std::endl;

#include <vector>
using std::vector;



size_t get_index(const size_t x, const size_t y, const size_t z, const size_t x_res, const size_t y_res, const size_t z_res)
{
    return z * y_res * x_res + y * x_res + x;
}

    

int main(void)
{
    const size_t x_res = 10;
    const size_t y_res = 10;
    const size_t z_res = 10;

    // Use new[] to allocate, and memset to clear
    //float* vf = new float[x_res * y_res * z_res];
    //memset(vf, 0, sizeof(float) * x_res * y_res * z_res);

    // Better yet, use a vector
    vector<float> vf(x_res*y_res*z_res, 0.0f);

    for (size_t x = 0; x < x_res; x++)
    {
        for (size_t y = 0; y < y_res; y++)
        {
            for (size_t z = 0; z < z_res; z++)
            {
                size_t index = get_index(x, y, z, x_res, y_res, z_res);

                // Do stuff with vf[index] here...
            }
        }
    }

    // Make sure to deallocate memory
    // delete[] vf;

    return 0;
}
Related