现有内存中的 C++ 多维数组 [英] C++ Multidimensional array in existing memory

查看:24
本文介绍了现有内存中的 C++ 多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这不是 thisthis 是指固定大小,问题不在于理解指针是如何存储的,而在于编译器是否可以自动执行手动功能).

(This is not a duplicate of this or this that refer to fixed sizes, the issue is not to understand how pointers are stored, but if the compiler can automate the manual function).

基于 this SO question 存储多维数组顺序.

Based on this SO question multidimensional arrays are stored sequentially.

// These arrays are the same
int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}}; 
int array2[6] = { 0, 1, 2, 3, 4, 5 }; 

但是我试图在预先分配的内存中创建一个二维浮点数组:

However I'm trying to create a 2 dimension array of floats in pre-allocated memory:

float a[5][10] 
float b[50]; // should be same memory

然后我正在尝试:

vector<char> x(1000);
float** a = (float**)x.data();
a[0][1] = 5;

上面的代码崩溃了,显然是因为编译器不知道数组的大小来分配它在内存中,就像第一个例子中编译器级别的已知数组一样.

The above code crashes, obviously because the compiler does not know the size of the array to allocate it in memory like in the compiler-level known array in the first example.

有没有办法告诉编译器在不手动计算指针的情况下在顺序内存中分配多维数组(例如,通过手动移动索引并调用placement new)?

Is there a way to tell the compiler to allocate a multi dimensional array in sequential memory without manually calculating the pointers (say, by manually shifting the index and calling placement new for example)?

目前,我是手动完成的,例如:

Currently, I'm doing it manually, for example:

template <typename T> size_t CreateBuffersInMemory(char* p,int n,int BufferSize)
{
    // ib = T** to store the data
    int ty = sizeof(T);

    int ReqArraysBytes = n * sizeof(void*);
    int ReqT = ReqArraysBytes * (ty*BufferSize);
    if (!p)
        return ReqT;

    memset(p, 0, ReqT);
    ib = (T**)p;
    p += n * sizeof(void*);
    for (int i = 0; i < n; i++)
    {
        ib[i] = (T*)p;
        p += ty*BufferSize;
    }
    return ReqT;
}

非常感谢.

推荐答案

T[rows][cols] 数组分配为一维数组分配 T[rows * cols].

To allocate T[rows][cols] array as a one-dimensional array allocate T[rows * cols].

要访问该一维数组的元素 [i][j],您可以执行 p[i * cols + j].

To access element [i][j] of that one-dimensional array you can do p[i * cols + j].

示例:

template<class T>
struct Array2d {
    T* elements_;
    unsigned columns_;

    Array2d(unsigned rows, unsigned columns)
        : elements_(new T[rows * columns]{}) // Allocate and value-initialize.
        , columns_(columns)
    {}

    T* operator[](unsigned row) {
        return elements_ + row * columns_;
    }

    // TODO: Implement the special member functions.
};

int main() {
    Array2d<int> a(5, 10);
    a[3][1] = 0;
}

这篇关于现有内存中的 C++ 多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆