STL vector and push_back
- From: "Abstract Dissonance" <Abstract.Dissonance@xxxxxxxxxxx>
- Date: Thu, 29 Jun 2006 16:25:43 -0500
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
.
- Follow-Ups:
- Re: STL vector and push_back
- From: Martin Eisenberg
- Re: STL vector and push_back
- From: Tom Plunket
- Re: STL vector and push_back
- Prev by Date: Re: recursive algorithm help
- Next by Date: Re: ls lacking a feature?
- Previous by thread: date class C++, anyone?
- Next by thread: Re: STL vector and push_back
- Index(es):
Relevant Pages
|