I am new to C ++ and usually Java code. I find it difficult to understand how containers in C ++ are the same and different from what I use in Java.
For the project that I am currently doing, I created my own data structure called solar_body. Each of them contains a name, mass, radius and 3 data structures that I created using position_t, velocity_t and acceleration_t. We hope that these names are self-explanatory.
I use a vector to store a collection of solar_body objects in my program. It seems I found a problem using for each loop that I know from Java, and was hoping that someone could explain what happened.
I run a loop through a vector calling the update method (solar_body.update ()) for each object. This calculates the new speed and position based on the current acceleration for this iteration. When I first installed this, I made my for loop as follows:
for (solar_body body: bodies) {
body.update(); }
When I do this and print variables, speeds and positions are updated. However, during my next iteration of the while-loop, the new values โโdisappeared and they reverted to the same old values. It seems that the for-each loop works on a copy of the solar_body object, not the original.
Out of curiosity, I changed the for loop:
for (int i=0; i<bodies.size(); i++) {
bodies.at(i).update(); }
It worked as I expected. In Java, there are practically no differences in the use of these two loops. What happened in this situation that I do not understand?
Thanks in advance for your help.
source
share