列表中的C ++对象变量在迭代期间不会更新 [英] C++ Object variables in list don't update during iteration

查看:147
本文介绍了列表中的C ++对象变量在迭代期间不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当遍历列表时,列表中对象的变量不会更新,调试时看起来变量只是临时更新,直到循环结束。为什么是这样?我一直在寻找很长时间。

When iterating through a list, the variables of the object in the list won't update, with debugging it looked like the variables only updated temporarily until the loop ended. Why is this? I've been looking for a very long time.

for (std::list<GUI>::iterator it = allguis.begin(); it != allguis.end(); ++it) {
    GUI gui = *it;
    speed = 5
   if (gui.activated) {
    gui.position.x = gui.position.x + gui.distanceX * speed;
    gui.position.y = gui.position.y + gui.distanceY * speed;
           }
   }                

GUI类:

class GUI
{
public:
    sf::Vector2f position = sf::Vector2f(0,0);
    int sizex;
    int sizey;
    bool activated;
    float rotation;
    int damage;
    float distanceX;
    float distanceY;

};


推荐答案

GUI gui = * it ; 创建一个使用存储在容器中的值的副本初始化的局部变量。你应该改用refence:

GUI gui = *it; creates a local variable initialized with a copy of the value stored in container. You should use a refence instead:

GUI & gui = *it;

或者你可以使用C ++ 11风格的循环:

Or you can use C++11-style loop:

speed = 5; // no point in updating it on every iteration
for(auto & gui: allguis)
{
    if(gui.activated)
    {
        gui.position.x = gui.position.x + gui.distanceX * speed;
        gui.position.y = gui.position.y + gui.distanceY * speed;
    }
}  

这篇关于列表中的C ++对象变量在迭代期间不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆