我有以下内容
std::vector<Cube> well = vector<Cube>();
createCube(well, x, y, z, id);
Run Code Online (Sandbox Code Playgroud)
后来我尝试将Cube插入到这样的矢量中,
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);
}
Run Code Online (Sandbox Code Playgroud)
我得到输出loc = 0.
为什么它不是我的Vector的新Cube?
您将按值传递给createCube函数; 这意味着您的矢量被复制,然后该元素被添加到新的矢量而不是原始矢量.您可以通过将方法签名更改为:
void Viewer::createCube(std::vector<Cube>& vec, int x, int y, int z, int id)
Run Code Online (Sandbox Code Playgroud)