STL vector and push_back



I'm working with STL vector and trying to get in the habit of using
iterators to work through the vector instead of "direct indexing". It
doesn't seem all that difficult as they seem to work like pointers but I'm
having a problem when I create an iterator for a vector then push something
onto the end of vector with push_back it will "destory" my iterator(I'm not
sure exactly what happens but the iterator becomes useless... not sure if it
gets set to s.end() or what).

Now I might see why this would happen because you are changing the vector
and it could cause problems in certain situations but I need to keep the
current position of the iterator. This could easily be done using indexing
but I'm trying to get away from that.

My code is

void PropagateCarry(vector<int> &s, vector<int>::iterator &i)

{

if (i == s.end()) return;

if (i == (s.end() - 1)) { ((*i)--); s.push_back(1); return; }



int k = 1;

(*i)--;



(*(i+1)) += k;

if ((*(i+1)) > (*i))

{

k = (*(i+1)) - (*i);

(*(i+1)) = (*i);



if (i + 2 >= s.end())

{

// Here the iterator becomes usless and caues the recursive call to
crash...

s.push_back(k);

}

else

{

(*(i+2)) += k;

}

PropagateCarry(s, i+1);

}

};



Thanks,

Jon


.



Relevant Pages

  • Re: STL vector and push_back
    ... Abstract Dissonance wrote: ... iterators to work through the vector instead of "direct indexing". ... doesn't seem all that difficult as they seem to work like pointers but I'm ... iterator(I'm not sure exactly what happens but the iterator becomes ...
    (comp.programming)
  • Re: STL vector and push_back
    ... Abstract Dissonance wrote: ... iterators to work through the vector instead of "direct indexing". ... sure exactly what happens but the iterator becomes useless... ... and your pointer no longer points to anything useful. ...
    (comp.programming)
  • Copy algorithm with insert iterators...
    ... I have gotten into the habit of often using copy along with an insert ... iterator. ... There are scenarios where I process quite a lot of data this way. ... container with elements in place? ...
    (comp.lang.cpp)
  • Re: Need Container for Large Binary String
    ... > point, I'm most likely going with the STL vector, using a for-loop to ... Use the constructor of vector that takes a begin iterator and an end ... Pointers are iterators, so you can say ...
    (microsoft.public.vc.mfc)
  • Re: Need Container for Large Binary String
    ... > point, I'm most likely going with the STL vector, using a for-loop to ... Use the constructor of vector that takes a begin iterator and an end ... Pointers are iterators, so you can say ...
    (microsoft.public.win32.programmer.tools)