将Vertex的std :: vector转换为float的最佳方式是什么?我有vtx作为我的原始数据,其中包含两个顶点的位置,正常和紫外线,我有std ::向量的顶点v与相同的位置,正常和紫外线。我试图实现的是使用std :: vector v获得与vtx2相同的内存布局和数据。我尝试使用memcpy将内存从v复制到vtx2,但是当我打印它们时,它们以不同的方式排序。将Vertices图形的std :: vector转换为float *
#include <iostream>
#include <vector>
using namespace std;
struct Vector3
{
float x;
float y;
float z;
};
struct Vector2
{
float x;
float y;
};
struct Vertex
{
Vector3 position;
Vector3 normal;
Vector2 uv;
};
int main(int argc, char *argv[])
{
const int n = 16;
float* vtx = new float[n];
// Vertex 1
// Position
vtx[0] = 1.0f;
vtx[1] = 2.0f;
vtx[2] = 3.0f;
// Normal
vtx[3] = 0.1f;
vtx[4] = 0.2f;
vtx[5] = 0.3f;
// UV
vtx[6] = 0.0f;
vtx[7] = 1.0f;
vtx += 8;
// Vertex 2
// Position
vtx[0] = 4.0f;
vtx[1] = 5.0f;
vtx[2] = 6.0f;
// Normal
vtx[3] = 0.2f;
vtx[4] = 0.3f;
vtx[5] = 0.4f;
// UV
vtx[6] = 0.0f;
vtx[7] = 1.0f;
vtx += 8;
for (int i = n; i>0; i--)
{
cout << *(vtx + i * -1) << endl;
}
vector<Vertex> v;
Vertex vt;
// Vertex 1
// Position
Vector3 pos1 = {1.0, 2.0, 3.0};
vt.position = pos1;
// Normal
Vector3 normal1 = {0.1, 0.2, 0.3};
vt.position = normal1;
// UV
Vector2 uv1 = {0.0, 1.0};
vt.uv = uv1;
v.push_back(vt);
// Vertex 2
// Position
Vector3 pos2 = {4.0, 5.0, 6.0};
vt.position = pos2;
// Normal
Vector3 normal2 = {0.2, 0.3, 0.4};
vt.position = normal2;
// UV
Vector2 uv2 = {0.0, 1.0};
vt.uv = uv2;
v.push_back(vt);
float* vtx2 = new float[n];
memcpy(vtx2, &v[0], v.size() * sizeof(Vertex));
for (int i = n; i>0; i--)
{
cout << *(vtx2 + i * -1) << endl;
}
delete[] vtx;
delete[] vtx2;
return 0;
}
你想用它做什么?你可以访问'data'成员来获得一个指向底层数组的指针,但这是不变的,你不应该直接改变它。 – Donnie
我有一些VBO,最初我使用float *。我试图将它们转换为Vertices的std :: vector,并保留相同的内存布局。 – sabotage3d
*为什么*你想保留内存布局?通常当你使用标准容器时,内存布局不是你关心的问题。 – Beta