I'm writing a program that simulates road traffic, I have a vector of integers inside a structure, which is itself the elements of a vector. Everything works fine except the iterator i use to delete elements of the inbedded integer vector seems to be going out bound and then when it trys to delete the element the program crashes.

The code that does this is here:

            if (CAR_VEC[i].VELOCITY==0){ 
                                    vector<int>::iterator STEP;

            for (STEP=CAR_VEC[i].PASSD.begin(); STEP!=CAR_VEC[i].PASSD.end(); ++STEP){

                                                    if ( *STEP==ROAD_STOP[j]->NUM){
                                                        cout <<"ok- bus:"<<i<<" pass:"<< *STEP<<" stop:"<<ROAD_STOP[j]->NUM<<endl;
                                                        CAR_VEC[i].PASSD.erase(STEP); //something wrong with this line
                                                        }}

Where CAR_VEC is vector < CARS > CAR_VEC;, cars being the struct which PASSD is inside.

The cout's are just so I can check that the integers I want are sensible, which they are. I've tried everything and nailed down the problem to something being deleted that isn't there. Yet I can't see why the iterator is going out of bounds. Is it something to do with the vector being inbedded in a structure, in which case do I need to declare the iterator as part of the larger vector CAR_VEC.

ie CAR_VEC[i].vector<int>::iterator STEP; although I've tried this and it doesn't compile.

It should probably be:

STEP = CAR_VEC[i].PASSD.erase(STEP);

That hasn't changed the problem. If it's any help this is the output the program gives before it fails.

bus:21
2
2
2
0
0
0
2

ok- bus:21 pass:2 stop:2
erased
ok- bus:21 pass:2 stop:2
erased
ok- bus:21 pass:2 stop:2
erased
ok- bus:21 pass:2 stop:2

Passenger_vector has exited due to signal 11 (SIGSEGV).

Strangely it works fine as long as the number being deleted isn't the last one on the list.

Got it. It was a combination of two things.
Firstly, you do need to say STEP = ....erase(STEP).
Secondly, if you do erase an element, you must not increment STEP.

vector<int>::iterator STEP;
for (STEP=CAR_VEC[i].PASSD.begin(); STEP!=CAR_VEC[i].PASSD.end(); ) {
  if ( *STEP==ROAD_STOP[j]->NUM){
    cout <<"ok- bus:"<<i<<" pass:"<< *STEP
         <<" stop:"<<ROAD_STOP[j]->NUM<<endl;
    STEP = CAR_VEC[i].PASSD.erase(STEP);
  }
  else
    ++STEP
}

Wicked, nice one that's fixed it. That does make sense, I thought that part of the benefit of using iterators was that it would maintain the positions of the elements until the changes were all made.

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.