2017-03-06 5 views
0

を構造体の配列を入力します。私はこの構造を有する動的

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の配列に指定したベクターを入力したいと思います。どうやってやるの?

Vertex points[numVertices]; 

それvarが一定の値を持っていない: 私は、このように配列を初期化しようとしました。

ありがとうございました。

+0

'std :: vector 'を使用できないのはなぜですか? – mpiatek

+0

その後、 'reinterpret_cast (ポイント)'を使う必要があります。これは配列であり、ベクトルではありません。 – Pino

+1

'vector :: data()'は生の配列(正確な最初の要素へのポインタ)のように動作します。あなたは 'BYTE * 'などにキャストするためにそれを使うことができます。 –

答えて

1

std::vectorは、ダイナミックアレイを作成する最適なオプションです。

  1. あなたのためのメモリ管理が必要です。
  2. std::vector::datastd::vector::operator[]std::vector::iteratorを使用して配列の内容にアクセスできます。
  3. std::vectorの各要素は、範囲forループを使用して処理できます。

代わりの

Vertex points[numVertices]; 

あなたは生の配列を使用する必要がある場合、あなたはこれを試すことができ

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

を使用しています。 XMFLOAT3、XMFLOAT2のようなものであると仮定すると、次のとおりです。あなたがVertex **points = initVertex(numVertices)を使用し、各要素を逆参照することができます

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; 
} 

:として

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; 
}; 

は、動的に要素を割り当て、初期化することによって頂点配列を初期化するために、init関数を定義します。

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)それを呼び出すと、各要素にアクセスするために、配列のインデックスを使用する:あなたはVertex *pointsを持たなければならない場合

は、あなたは、頂点の初期化配列を作成するには、この機能を使用することができます。

関連する問題