c++ - 我可以安全地复制 vector<array> 吗?

标签 c++ arrays vector memcpy

我有一个vector<array<float,3>>用作我的渲染的 3D 坐标列表。
我可以简单地将 memcpy 与 sizeof(array<float,3>) * vector.size() 一起使用吗作为count争论? Vector的内存可以安全复制吗?

€dit:这是我的代码片段。 我的问题现在措辞有点不正确。

vector<array<float,3>> vertexPositions;
//read VertexPositions, one line represents a vertex position and put them into vertexPositions with push_back();

D3D11_BUFFER_DESC bufferDesc;
//initialize Buffer Description;

D3D11_SUBRESOURCE_DATA bufferInitialData;
bufferInitialData.pSysMem = vertexPositions.data(); //pSysMem is a void* and expects a sequence of floats

pSysMem就是一个void*该结构有一个额外的大小参数,我将其设置为 sizeof(array<float,3>) * vector.size()

最佳答案

Is the memory of vector safe to copy?

是的, vector 在这里没有做任何特殊的事情,元素的打包方式与数组相同。您可以很容易地看到这一点,因为 data() 返回一个可以作为数组访问的指针(对于 [0][myvec.size() - 1]),直到执行使返回无效的操作(例如销毁 vector 或调整 vector 大小)。

I want the floats to be tightly packed (since they will be sent to the GPU), does this allow me to do that?

因此,这基本上意味着确保您存储在 vector 中的类型满足要求。 (例如,您实际上需要 3 浮点 RGB 格式,而不是整数格式或 RGBA 或 RGBX 4 元素格式之一)。根据您使用的 API,您甚至可以直接为其提供 vector 数据,而无需复制到单独的数组(例如 ID3D11Device::CreateBuffer 接受 pInitialData 并且如果您在 vector 中存储正确的类型,您只需将 pSysMem 设置为 myvector.data())。

关于c++ - 我可以安全地复制 vector<array> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59821127/

相关文章:

c++ - 如何避免动态分配内存 C++

php - 如何按键查找最大和最小日期

嵌入许多简单变量和一个嵌套结构的结构的 C++ 深度复制..(memcpy?)

c++ - 二进制搜索算法 C++

php - 一定要有唯一的数组条目

c++ - vector 和赋值运算符

c++ - 如何从其他结构访问 protected 结构变量

c++ - 我正在尝试使用类 vector 编写代码

python - 使用 OpenCV 3.4 加载 CNN tensorflow 模型时出错

java - 使用线程在数组中搜索元素