| re: adding/removing elements from std::vector
"Tino" <tino52@yahoo.com> wrote in message
news:f9d112e6.0402201354.22f5d9bc@posting.google.c om...[color=blue]
> I have a std::vector<int> which, after some initialization, has a
> fixed number of elements...after initialization I must do the
> following repeatedly: I remove an element which could be anywhere in
> the vector, and add another element which will always be at the end,
> ie.
>
> vector<int> v;
> int i, x;
>
> ... initialization
>
> v.erase( v.begin() + i );
> v.push_back( x );
>
> My question is whether there is a better way to do this...since I[/color]
know[color=blue]
> that there will always be a sequence of removing an element followed
> by appending an element to the end, can I do it in a way which[/color]
doesn't[color=blue]
> use either erase or push_back? Or are most implementations such[/color]
that[color=blue]
> this shouldn't be a problem? Since this erase/push_back sequence[/color]
will[color=blue]
> happen many times, I would like to avoid any possible memory
> management since the size of the vector will never really change.[/color]
Iterators pointing to poisitions before the removed element are
required not to be invalidated by removal, which means that the
removal will not cause any deallocation and reallocation of the
vector's underlying storage. When you immediately append another
element, it should be occupy an already allocated position.
The main expense is the assignments required to effecively shift the
elements above the removal point down one index. This is what you
might want to avoid, perhaps by using a list, depending on your other
requirements.
Jonathan |