用foreach循环更新std :: list中的每个值C ++ [英] Update each value in a std::list with a foreach loop C++
问题描述
我在C ++中有一个 std :: list
,我正在尝试使用 for(类型t:列表)
用于更新每个对象的值的操作.因此,我有一个称为球的列表,每个球都有一个位置.我的循环代码是:
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);
computeBallPosition取一个球并根据经过的时间返回其新位置.
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.
推荐答案
您正在复制原始对象,请使用引用
You're taking a copy of original object, use a reference
for(OpenGLView::AssetInstance& ball : balls)
ball.position = calculateBallPosition(ball);
或者简单地
for( auto& ball : balls)
ball.position = calculateBallPosition(ball);
这篇关于用foreach循环更新std :: list中的每个值C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!