首页 > 解决方案 > 正确分配 std::vector

问题描述

我在将我的 std::vector 交给另一个班级时遇到问题。我将数据放入 std::vector 并将其放入名为“Mesh”的类中。“网格”变成了“模型”。

// Store the vertices
std::vector<float> positionVertices;

positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back(-0.5f);
positionVertices.push_back( 0.5f);

// Put them into a mesh and the mesh into a model
Mesh mesh = Mesh(positionVertices);
Model model = Model(mesh);

在模型类中,我取回网格的位置顶点并将其转换为 float[]。但看起来,我分配 std::vector 的方式是错误的,因为在模型类中检查 std::vector 时,它的大小为 0。

// Store the vertices
float* dataPtr = &data[0];
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), dataPtr, GL_STATIC_DRAW);

如何将数据正确地带入其他类?

我也不确定网格类的构造函数的工作方式。网格.h:

// Mesh.h
class Mesh
{
public:
    std::vector<float> positionVertices;

    Mesh(std::vector<float>);
    ~Mesh();
};

Mesh.cpp:

// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) : positionVertices(Mesh::positionVertices)
{
}

模型.h:

// Model.h
class Model
{  
public:
Mesh mesh;
unsigned int vertexArray;
unsigned int vertexCount;

Model(Mesh);
~Model();

void storeData(std::vector<float> data, const unsigned int index, const unsigned int size);
};

模型.cpp:

// Model.cpp
Model::Model(Mesh mesh) : mesh(Model::mesh)
{ ... }

标签: c++opengl

解决方案


// Mesh.cpp
Mesh::Mesh(std::vector<float> positionVertices) :
positionVertices(Mesh::positionVertices) // Here's the problem
{
}

positionVertices初始化器列表中的是 Mesh::positionVertices因此您将其分配给自身。

采用

positionVertices(positionVertices)

还有,改变

Mesh::Mesh(std::vector<float> positionVertices) :

Mesh::Mesh(const std::vector<float>& positionVertices) :

所以你不会制作不必要的矢量副本。


推荐阅读