【发布时间】:2015-06-15 04:59:16
【问题描述】:
这听起来像是一个非常基本的问题,但我已经尝试修复一个简单的错误一个多小时了,但我似乎无法理解发生了什么。
我的头文件中有以下结构声明:
struct StudentBody
{
string name;
Vec2 position;
bool disabled;
StudentBody(string name, Vec2 position) : name(name), position(position) {}
};
这个结构被填充到一个向量类型中:
std::vector<StudentBody> students_real;
像这样:
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))
};
默认情况下,所有学生的“已禁用”设置为 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);
}
}
这里的问题是“禁用”标志没有保持为真。当我首先检查条件时,它是错误的。然后我也检查我的第二个条件,如果它满足,我将它设置为 true。但是,下次启动此 for 循环时,条件会返回 false。
这让我相信我的"auto student_to_check = *it;" 给了我一份结构的副本来处理它,而不是结构本身?或者发生了什么?为什么我不能修改向量内结构的值?
【问题讨论】:
-
auto student_to_check = *it=>auto& student_to_check = *it -
需要
auto& student_to_check = *it; -
StudentBody的构造函数不保证“默认情况下所有学生的“禁用”设置为 false” -
您也可以使用基于范围的 for 循环,例如:
for(auto&& student_to_check : students_real)