std :: vector和多维数组的连续内存 [英] std::vector and contiguous memory of multidimensional arrays

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

问题描述

我知道标准不会强制 std :: vector 分配连续的内存块,但所有实现都会遵循这一点。 p>

假设我想创建一个多维静态数组的向量。为了简单起见,考虑2维,长度为N的向量。我想创建一个具有N个元素的向量,例如 int [5]



我可以确定所有N * 5个整数现在在内存中是连续的吗?所以我原则上可以访问所有的整数简单地通过知道第一个元素的地址?这个实现是否依赖?



作为参考,我当前在连续内存块中创建一个2D数组的方法是首先创建一个长度为N的float(动态)数组,在一个数组中分配所有N * 5个浮点,然后将每个第5个元素的地址复制到 float * 的第一个数组。

解决方案


引用我目前在连续内存块中创建2D数组的方法是先创建一个长度为N的float *(动态)数组,在一个数组中分配所有N * 5个浮点,然后将每个第5个元素的地址复制到float *的第一个数组。




这不是一个二维数组,这是一个指针数组。如果你想要一个真正的二维数组,这是如何做:

  float(* p)[5] = new float [ N] [5]; 

p [0] [0] = 42; //访问第一个元素
p [N-1] [4] = 42; //访问最后一个元素

delete [] p;

请注意,只有一个分配。我可以建议您阅读有关使用C ++中的数组的更多信息吗?


I know that the standard does not force std::vector to allocate contiguous memory blocks, but all implementations obey this nevertheless.

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

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?

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*.

解决方案

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;

Note there is only a single allocation. May I suggest reading more about using arrays in C++?

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

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