adding/removing elements from std::vector

T

Tino

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 know
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 doesn't
use either erase or push_back? Or are most implementations such that
this shouldn't be a problem? Since this erase/push_back sequence will
happen many times, I would like to avoid any possible memory
management since the size of the vector will never really change.

Regards,
Tino
 
J

Jonathan Turkanis

Tino said:
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 know
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 doesn't
use either erase or push_back? Or are most implementations such that
this shouldn't be a problem? Since this erase/push_back sequence will
happen many times, I would like to avoid any possible memory
management since the size of the vector will never really change.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top