Update each value in a std::list with a foreach loop C++

强颜欢笑 提交于 2021-02-05 10:57:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!