C++ 向量不插入

C++ vector not inserting

我有以下

std::vector<Cube> well = vector<Cube>();
createCube(well, x, y, z, id);

稍后我尝试像这样在向量中插入一个立方体,

void Viewer::createCube(std::vector<Cube> vec, int x, int y, int z, int id) {
    float rgb[] = {0.0f, 0.0f, 1.0f};
    vec.push_back(Cube(QMatrix4x4(), -1));
    int loc = vec.size() - 1;
    std::cout << "loc:" << loc << std::endl;
    vec.at(vec.size() - 1).matrix.translate(x,y,z);
}

我得到输出 loc = 0。

为什么它不是我的 Vector 的新 Cube?

您正在按值将向量传递给 createCube 函数;这意味着您的矢量被复制,然后元素被添加到新矢量而不是原始矢量。您可以通过将方法签名更改为:

来修复它
void Viewer::createCube(std::vector<Cube>& vec, int x, int y, int z, int id)