std::list 迭代中项目的指针

发布于 2024-08-12 17:43:28 字数 438 浏览 1 评论 0原文

我正在开发一个非常基本的游戏,并且我有一个与我的游戏相关的对象的 std::list 集合。我将其声明为:

std::list<Target> targets;

当我迭代它时,使用

for (std::list<Target>::iterator iter = targets.begin(); iter != targets.end(); iter++) {
        Target t = *iter;
                t.move();
}

“我的对象”不会在 GUI 上更新。但是,用 targets.front().move() 替换迭代循环后,我的一个对象可以正确移动。我认为这是因为我没有使用指针迭代集合。谁能解释一下这是如何完成的?谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千里故人稀 2024-08-19 17:43:28

您要复制对象,请按以下方式操作:

*iter.move()

如果您使用 Target t = *iter;,您实际上是在复制对象并移动它,而不是移动您想要的对象。

正如 xtofl 所说(thx),您也可以获得参考。

Target &t = *iter;
t.move();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文