Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't the items in my vector change during for-each loop in C++?

I'm new to C++ and typically code in Java. I am having a difficult time understanding how the containers in C++ are the same and different than I'm used to in Java.

For the project I am doing right now, I have made my own data structure called a solar_body. Each of these contains a name, mass, radius, and 3 data structures I made called position_t, velocity_t, and acceleration_t. Hopefully these names are self explanatory.

I am using a vector to hold the collection of solar_body objects in my program. I seem to have found an issue using the for-each loop I know from Java and was hoping someone could explain what happened.

I run a loop through the vector calling the update method (solar_body.update()) on each object. This calculates the new velocity and position based on the current acceleration for that iteration. When I first set this up, I did my for-loop like this:

for (solar_body body: bodies) {
  body.update(); }

When I do this and print the variables, the velocities and positions are updated. However, during my next while-loop iteration, the new values are gone and they are back to the same old values. It seems as if the for-each loop is operating on a copy of the solar_body object and not the original.

Out of curiosity, I changed my for loop to this:

for (int i=0; i<bodies.size(); i++) {
  bodies.at(i).update(); }

This worked as I would have expected. In Java, there is really no difference in practice in using these two loops. What happened in this situation that I don't understand?

Thanks in advance for the help.

like image 645
user2271605 Avatar asked Dec 26 '22 14:12

user2271605


1 Answers

for (solar_body body : bodies)

This iterates by value; that is, it creates a copy of an element of bodies, and places it in body for the duration of the iteration. Then it goes on to the next element, and so on. To iterate by reference, so that you can modify the elements, you want the following:

for (solar_body& body : bodies)
like image 133
Brian Bi Avatar answered Jan 12 '23 00:01

Brian Bi