Reputation: 23
I'm learning C++ and have come to a bit of a halt. I'm trying to iterate over a vector with a range-based for loop and update a property on each of the objects that belong to it. The loop is inside of an update function. The first time it fires, it works fine; I can see the property gets updated on each member of the vector. However, the next time the for loop is initiated, it's still updating the original data, as if the previous run did not actually update the source values. Is my range declaration configured correctly? Pointers are still a bit of a mystery to me. In general I'd be very thankful for any help!
for (Point &point : points)
{
Vector3 position = point.position;
if (position != destination)
{
Vector3 move = Vector3::Zero;
if (position.x > destination.x)
move.x -= 1.0;
if (position.x < destination.x)
move.x += 1.0;
if (position.y > destination.y)
move.y -= 1.0;
if (position.y < destination.y)
move.y += 1.0;
if (position.z > destination.z)
move.z -= 1.0;
if (position.z < destination.z)
move.z += 1.0;
position += move;
}
}
Upvotes: 2
Views: 701
Reputation: 24836
You are modifying position
, but not point.position
, because position
is a copy of point.position
.
If you instead want to make position
a reference to point.position
, then you must change the line
Vector3 position = point.position;
to
Vector3 &position = point.position;
That way, modifying position
will also modify point.position
.
Upvotes: 0
Reputation: 25388
Vector3 position = point.position;
makes a copy of point.position
. The following code then updates this copy, which in turn is thrown away when it goes out of scope at the end of the if
statement.
The solution is simple enough - use a reference instead: Vector3 &position = point.position;
. The rest of the code can be left as-is.
Upvotes: 4