How can I change the attribute of an object in a for loop using iterators?

This is a story about a car entering a queue at an intersection.

So, for each road there are different lanes (iterator it

), and for each lane there are different cars (iterator it2

).

void function(Road& R, int timestep) {

    vector<int> lane = R.void1() {
    for(vector<int>::iterator it = lane.begin() ; it != lane.end() ; it++) {

        vector<Car> cars = R.void2((*it));
        for(vector<Car>::iterator it2 = cars.begin() ; it2 != cars.end() ; it2 ++) {

            if((*it2).get_travel_time() >= R.get1((*it))
                  (*it2).init_travel_time();
            else
                  (*it2).incr_travel_time(timestep);
        }
    }
}

      

where the init_travel_time

sets travel

of (*it)

before 0

and which incr_travel_time(timestep)

increases the same attribute travel

, (*it)

on timestep

.

The problem I see is that the copy of the (*it2)

car is enlarged and not the car in the line R.void2((*it))

.

Instead, to scale up directly on the car, I tried:

void function(Road& R, int timestep) {      
    for(vector<int>::iterator it = R.void1().begin() ; it != R.void1().end() ; it++) {    
        for(vector<Car>::iterator it2 = R.void2((*it)).begin() ; it2 != R.void2((*it)).end() ; it2 ++) {

                if((*it2).get_travel_time() >= R.get1((*it))
                      (*it2).init_travel_time();
                else
                      (*it2).incr_travel_time(timestep);
            }
        }
    }

      

but i got the following error:

vector iterator is incompatible

which is understandable ( vector iterators are incompatible ).

I think I cannot use the answers until my vector cannot be const (I change its attribute), and until the second answer takes me back to my first sentence.

+3


source to share


1 answer


To change the actual vector contained in the Road and avoid creating a copy, create references to vectors in your first version:

void function(Road& R, int timestep) {

    vector<int>& lane = R.void1();
    for(vector<int>::iterator it = lane.begin() ; it != lane.end() ; it++) {

        vector<Car>& cars = R.void2(*it);
        for(vector<Car>::iterator it2 = cars.begin() ; it2 != cars.end() ; it2 ++) {

            if(it2->get_travel_time() >= R.get1(*it))
                  it2->init_travel_time();
            else
                  it2->incr_travel_time(timestep);
        }
    }
}

      

Also, void1 and void2 must return references (if they are not)



vector<int>& Road::void1();
vector<Car>& Road::void2(int lane);

      

I've also removed redundant parentheses in your code to make it easier to read.

+3


source







All Articles