Pointer for item in iteration over std::list
I'm working on a very basic game and I have a std::list collection of objects that pertain to my game. I declared it as:
std::list<Target> targets;
When I iterate over it, using
for (std::list<Target>::iterator iter = targets.begin(); iter != targets.end(); iter++) {
Target t = *iter;
t.move();
}
My objects aren't updating on the GUI. However, replacing the iterating loop with a targets.front().move()
, my one 开发者_如何学运维object moves correctly. I think this is because I am not iterating over the collection using pointers. Can anyone explain how that is done? Thanks.
You are copying the objects, do it this way:
*iter.move()
If you use Target t = *iter;
you are essentially making a copy of your object and moving it, instead of moving your intended object.
As xtofl said(thx) you can get the reference as well.
Target &t = *iter;
t.move();
精彩评论