Home > Blockchain >  Variable passed-by-reference is changed in function scope but not in main scope
Variable passed-by-reference is changed in function scope but not in main scope

Time:09-29

I'm trying to alter a given grid of vectors into a heightmap, which I do by passing a vector of vertices by reference to a function which should calculate the height for each vertex and change it. However, when printing the height of the new vertices in the main scope, all are 0, whereas if I print the height of the vertices just after I calculate them, I get the correct result.

int main(){
 std::vector<glm::vec3> vertinfo = generate_grid(4, 4, 2.0f, 2.0f); //generates the grid
 generate_randomheightmap(vertinfo); //SHOULD modify the height of the vertices
//printing the y value of any of the vertices here will result in 0 (the unchanged value)
...
}
void generate_randomheightmap(std::vector<glm::vec3>& base, uint32_t layers){
 for (glm::vec3 vertex : base){
  vertex.y  = vertex.x * vertex.z;
  //printing the y value of the vertex here will result in the correct calculated value
 }
}

Does this not work because the vec3 objects themselves are instead copied while the vector isn't? It would be incredibly annoying if I had to change the vec3's to vec3 pointers

CodePudding user response:

The problem is not in pass-by-reference into the function, but in the for loop. It should use a reference to the vector elements:

for (glm::vec3& vertex : base)
  • Related