c++ - Why is the boolean value within a structure within a vector not being updated? -
this might sound basic question, have trying fix simple bug on hour , can't seem understand what's happening.
i have following structure declaration in header file:
struct studentbody { string name; vec2 position; bool disabled; studentbody(string name, vec2 position) : name(name), position(position) {} };
this structure being filled vector of type:
std::vector<studentbody> students_real;
like this:
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)) };
by default of students have "disabled" set false.
then have "update" method gets triggered screen refresh rate, , within method have following code:
for (auto = students_real.begin(); != 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; //... custom condition here checks if "disabledstudent" should become false or stay 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); } }
the problem here "disabled" flag not staying true. when check condition @ first it's false. check second condition , if it's satisfied set true. next time loop started condition false.
this makes me believe "auto student_to_check = *it;"
gives me copy of structure handle not structure itself? or going on? why can't modify value of structure within vector?
this:
auto student_to_check = *it;
declares local variable copy of structure in vector. iterator points structure in vector, can use:
auto student_to_check = it;
and:
student_to_check->disabled = true;
or more following access in vector's structure. don't need local variable:
it->disabled = true;
even better use c++11's range-based loop, @sp2danny commented:
for(auto& student_to_check : students_real)
student_to_check
reference structure in vector instead of local copy, , rest of code remains is.
Comments
Post a Comment