为什么向量内的结构中的布尔值没有被更新?

Poc*_*chi 0 c++ c++11

这可能听起来像一个非常基本的问题,但我现在试图修复一个简单的错误超过一个小时,我似乎无法理解发生了什么.

我的头文件中有以下结构声明:

struct StudentBody
{
    string name;

    Vec2 position;

    bool disabled;

    StudentBody(string name, Vec2 position) : name(name), position(position) {}
};
Run Code Online (Sandbox Code Playgroud)

这个结构被填充到一个类型的向量中:

std::vector<StudentBody> students_real;
Run Code Online (Sandbox Code Playgroud)

像这样:

students_real =
    {
        StudentBody("student1",Vec2(DISPLAY_WIDTH - 50, LOWER_MARGIN + 100)),
        StudentBody("student2",Vec2(DISPLAY_WIDTH - 100, LOWER_MARGIN + 100)),
        StudentBody("student3",Vec2(DISPLAY_WIDTH - 150, LOWER_MARGIN + 100)),
        StudentBody("student4",Vec2(DISPLAY_WIDTH - 200, LOWER_MARGIN + 100))
    };
Run Code Online (Sandbox Code Playgroud)

默认情况下,所有学生都将其"禁用"设置为false.

然后我有一个"更新"方法,用屏幕刷新率触发,在该方法中我有以下代码:

for (auto it = students_real.begin(); it != students_real.end(); it++)
        {
            auto student_to_check = *it;

            CCLOG("student %s disabled -> %i",student_to_check.name.c_str(),student_to_check.disabled);

            if (student_to_check.name == "student1" || student_to_check.disabled) {
                continue;
            }

            bool disableStudent = true;

            //... A custom condition here checks if "disabledStudent" should become false or stay as true...

            if (disableStudent)
            {
                CCLOG("Disabling %s",student_to_check.name.c_str());

                student_to_check.disabled = true;

                CCLOG("student %s disabled -> %i",student_to_check.name.c_str(),student_to_check.disabled);
            }
        }
Run Code Online (Sandbox Code Playgroud)

这里的问题是"禁用"标志不是真的.当我首先检查条件时它是错误的.然后我也检查了我的第二个条件,如果它满意,我将其设置为true.但是,下次启动此for循环时,条件将返回false.

这让我相信我"auto student_to_check = *it;"给了我一个处理它的结构的副本,但不是结构本身?或者发生了什么?为什么我不能修改向量中结构的值?

Mar*_*nen 6

这个:

auto student_to_check = *it;
Run Code Online (Sandbox Code Playgroud)

声明一个局部变量,它是向量中结构的副本.迭代器指向向量中的结构,因此您可以使用:

auto student_to_check = it;
Run Code Online (Sandbox Code Playgroud)

和:

student_to_check->disabled = true;
Run Code Online (Sandbox Code Playgroud)

或者更简单地通过以下方式访问向量结构中的任何内容.那你就不需要局部变量了:

it->disabled = true;
Run Code Online (Sandbox Code Playgroud)

更好的是使用C++ 11的基于范围的for循环,正如@ sp2danny评论的那样:

for(auto& student_to_check : students_real)
Run Code Online (Sandbox Code Playgroud)

student_to_check 将引用向量中的结构而不是本地副本,其余代码保持不变.