Walt Walt - 2 months ago 12
C++ Question

Changing an element within a vector of structures

I'm iterating through a set of elements within a vector of structures and want to change an element in one of the structures. When I write to the element to change the value, the update isn't retained. Here is what I have:

first, in a header file:

std::vector<Sched::ScheduledEvent_t> v_SchedEvents;
typedef std::vector<Sched::ScheduledEvent_t>::const_iterator event_iter;

then later in a .cpp module...

for (event_iter i = v_SchedEvents.begin(); i != v_SchedEvents.end(); ++i)
ScheduledEvent_t event = *i;

if(event.member == true) {
event.member = false;

The value of event.member for the given structure in the vector isn't staying false. When returning to this loop, the conditional statement is run again.

Could it have anything to do with the typedef for the iterator?



Two problems here.

1) You're making a copy:

ScheduledEvent_t event = *i;

event is a copy of the element in the vector. Modifing event won't affect it.

2) You are using a const_iterator which only allows reading the value, not changing it.

Use a iterator instead

typedef std::vector<Sched::ScheduledEvent_t>::iterator event_iter;

and use it directly:

if (i->member) { //  == true useless
    i->member = false;

Or a for-range loop if you have access to C++11 or more recent:

for (auto & event : v_SchedEvents) {
    if (event.member) {
        event.member = false;