动态填充结构数组

时间:2017-03-06 03:40:20

标签: c++ arrays struct

我有这个结构:

VSCODE

我需要用一些向量填充一个数组:

struct Vertex {
    Vertex(float px, float py, float pz,
           float nx, float ny, float nz,
           float tx, float ty) : position(px, py, pz),
                                 normals(nx, ny, nz),
                                 texCoords(tx, ty) {}
    XMFLOAT3 position;
    XMFLOAT3 normals;
    XMFLOAT2 texCoords;
};

数组的长度由

给出
std::vector<XMFLOAT3> positions;
std::vector<XMFLOAT3> normals;
std::vector<XMFLOAT2> texCoords;

我想用给定的向量填充int numVertices; 的数组。我怎样才能做到这一点? 我尝试用这种方式初始化数组:

struct Vertex

但是var没有常数值。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

std::vector是创建动态数组的最佳选择。

  1. 它为您负责内存管理。
  2. 您可以使用std::vector::datastd::vector::operator[]std::vector::iterator来访问数组的内容。
  3. 您可以使用范围 - std::vector循环处理for的每个元素。
  4. 而不是

    Vertex points[numVertices];
    

    使用

    std::vector<Vertex> points(numVertices);
    

答案 1 :(得分:0)

如果必须使用原始数组,可以试试这个。假设XMFLOAT3,XMFLOAT2如下所示:

struct XMFLOAT3 {
    XMFLOAT3(float x, float y, float z) : _x(x), _y(y), _z(z) {};
    float _x;
    float _y;
    float _z;
};

struct XMFLOAT2 {
    XMFLOAT2(float x, float y) : _x(x), _y(y) {};
    float _x;
    float _y;
};

通过动态分配和初始化元素来定义初始化顶点数组的初始化函数:

Vertex **
initVertex(int numVertices)
{
    Vertex **points = new Vertex *[numVertices];
    for (int i = 0; i < numVertices; ++i) {
        points[i] = new Vertex(positions[i]._x, positions[i]._y, positions[i]._x,
                normals[i]._x, normals[i]._y, normals[i]._z,
                texCoords[i]._x, texCoords[i]._y);
    }
    return points;
}

您可以使用Vertex **points = initVertex(numVertices)并取消引用每个元素。

如果必须有Vertex *points,则可以使用此函数创建初始化的顶点数组:

Vertex *
initVertex2(int numVertices)
{
    char *points_buf = new char[sizeof(Vertex) * numVertices];
    Vertex *points = reinterpret_cast<Vertex *>(points_buf);
    for (int i = 0; i < numVertices; ++i) {
        new (points_buf + i * sizeof(Vertex))
                Vertex(positions[i]._x, positions[i]._y, positions[i]._x,
                normals[i]._x, normals[i]._y, normals[i]._z,
                texCoords[i]._x, texCoords[i]._y);
    }
    return points;
}

并将其命名为Vertex *points = initVertex2(numVertices)并使用数组索引来访问每个元素。