std::vector 和多维数组的连续内存
我知道标准不会强制std::vector
分配连续的内存块,但所有实现都遵守这一点.
I know that the standard does not force std::vector
to allocate contiguous memory blocks, but all implementations obey this nevertheless.
假设我想创建一个多维静态数组的向量.为简单起见,考虑 2 个维度,以及一个长度为 N 的向量.也就是说,我希望创建一个包含 N 个元素的向量,例如 int[5]
.
Suppose I wish to create a vector of a multidimensional, static array. Consider 2 dimensions for simplicity, and a vector of length N. That is I wish to create a vector with N elements of, say, int[5]
.
我能确定所有 N*5 整数现在在内存中都是连续的吗?这样我原则上就可以通过知道第一个元素的地址来访问所有整数?此实现是否依赖?
Can I be certain that all N*5 integers are now contiguous in memory? So that I in principle could access all of the integers simply by knowing the address of the first element? Is this implementation dependent?
作为参考,我目前在连续内存块中创建二维数组的方式是首先创建一个长度为 N 的 float* 数组(动态),将所有 N*5 个浮点数分配到一个数组中,然后复制每个数组的地址float*
的第一个数组中的第 5 个元素.
For reference the way I currently create a 2D array in a contiguous memory block is by first making a (dynamic) array of float* of length N, allocating all N*5 floats in one array and then copying the address of every 5th element into the first array of float*
.
推荐答案
作为参考,我目前在连续内存块中创建二维数组的方式是首先创建一个长度为 N 的 float* 数组(动态),将所有 N*5 个浮点数分配到一个数组中,然后复制每个数组的地址第 5 个元素进入 float* 的第一个数组.
For reference the way I currently create a 2D array in a contiguous memory block is by first making a (dynamic) array of float* of length N, allocating all N*5 floats in one array and then copying the address of every 5th element into the first array of float*.
那不是二维数组,而是指针数组.如果你想要一个真正的二维数组,这就是它的完成方式:
That's not a 2D array, that's an array of pointers. If you want a real 2D array, this is how it's done:
float (*p)[5] = new float[N][5];
p [0] [0] = 42; // access first element
p[N-1][4] = 42; // access last element
delete[] p;
注意只有一个分配.我可以建议阅读更多关于在 C++ 中使用数组的内容吗?
Note there is only a single allocation. May I suggest reading more about using arrays in C++?
相关文章