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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With