正确分配 std::vector
Correct allocation for 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);
在模型类中,我将网格的位置顶点取回,并将其转换为浮点数[]。但看起来,我分配 std::vector 的方式是错误的,因为在模型类中检查 std::vector 时,它的大小为 0。
// Store the vertices
float* dataPtr = &data[0];
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), dataPtr, GL_STATIC_DRAW);
如何将数据正确引入其他类?
我也不确定网格类的构造函数的工作方式。网格:
// Mesh.h
class Mesh
{
public:
std::vector<float> positionVertices;
Mesh(std::vector<float>);
~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) :
因此,您不会对矢量进行不必要的复制。
相关文章:
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 连接和压缩标准::vector<std::字符串的最佳方法>
- C++从 std::vector<std::function<中删除 std::function>>
- 如何在构造函数初始值设定项列表中使用 n 个元素初始化 std::vector<std::time_t>
- 如何使用 CUDA 将 std::vector<std::string> 复制到 GPU 设备
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- 将 std::vector<std::unique_ptr<T>> 移动到 std::vector<std::shared_ptr<T>>
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 为什么转置这个 std::vector<std::vector<std::string> > 这么慢?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 在 boost::<double>asio::buffer 中使用像 std::vector<std::complex> 这样的参数
- 如何从 std::initializer_list<char const* 构建 std::vector<std::string>>
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- 在 std::vector<std::vector 中重新存储内部向量<TYPE>>
- 将 std::vector<std::string> 转换为 const char* const*
- 不能将结构push_back() 转换为 std::vector<std::shared_ptr<theStruct>> theVector
- SWIG:传递一个 std::vector< std::vector <double> >指向 python 的指针
- 将 std::vector<std::p air<const K, V>*> 转换为 std::vector<std::p air<const K, V>&g