c++ - 正确分配 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)
{ ... }
解决方案
// 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) :
所以你不会制作不必要的矢量副本。
推荐阅读
- python - 无法在 opencv python 中剪辑和保存 ROI/边界框
- python - 在 python 脚本中运行 bash source 命令
- node.js - 是否可以使用 pm2 reload 命令仅使用一个 pm2 fork 模式实例将停机时间归零?
- r - 在特定观察后提取第一个值
- http - 为什么flush会出现死锁?
- vim - 如何在不删除 Vim 中的括号的情况下删除括号内的所有内容?
- node.js - 如何使用 google oAuth 库在本地验证 Google 访问令牌
- ios - 在 React Native 中使用 Apple 登录返回 null
- python - 将 2 个一维数组转换为 1 个二维数组 Numpy Python
- python - ModuleNotFoundError:没有名为“deepface”的模块