问题
I've got a std::list
in C++ and I'm trying to use a
for(Type t : list)
operation to update the value of each object. So I have a list called balls and each ball has a position. My code to for the loop is:
for(OpenGLView::AssetInstance ball : balls)
ball.position = calculateBallPosition(ball);
where calculateBallPosition takes a ball and returns its new position based on time elapsed.
The problem I am running into is that the value of the elements in the list don't seem to be updating. When I check their values after the loop has run, it's the same as it was before. I'm guessing my mistake is in understanding the way this loop works, but I haven't been able to figure out how to fix it.
回答1:
You're taking a copy of original object, use a reference
for(OpenGLView::AssetInstance& ball : balls)
ball.position = calculateBallPosition(ball);
Or Simply
for( auto& ball : balls)
ball.position = calculateBallPosition(ball);
来源:https://stackoverflow.com/questions/26622385/update-each-value-in-a-stdlist-with-a-foreach-loop-c