q: STL vector manipulation

L

laniik

Hi. I have a STL vector of some relativly complicated objects

I was wondering if there was a good way to remove objects from the
middle of the vector.

Currently the only way I know how to remove element i is:

1. set the contents of the object at index i to the contents of the
last object
2. vector.pop_back();

but this is obviously annoying if my objects are not just simple
structs.

Thanks!

Oliver
 
B

Ben

Hi. I have a STL vector of some relativly complicated objects
I was wondering if there was a good way to remove objects from the
middle of the vector.



vec.erase(iter);

where vec is your vector, and iter is an iterator to the object you
wish to remove.


--
Clark S. Cox, III
(e-mail address removed)


Or you can do vec.erase(vec.begin() + i) // where i is an integer
for the element #

If you are doing a lot of deleting from the middle then you may not
want to use vectors. A list might be better for you, in which case,
you must use the erase that Clark suggested.

-Benjamin Dacko
 
I

Ioannis Vranos

Ben said:
vec.erase(iter);

where vec is your vector, and iter is an iterator to the object you
wish to remove.


--
Clark S. Cox, III
(e-mail address removed)


Or you can do vec.erase(vec.begin() + i) // where i is an integer
for the element #


Which is the same, an iterator to the object.
 
S

Stephen Howe

laniik said:
Hi. I have a STL vector of some relativly complicated objects

I was wondering if there was a good way to remove objects from the
middle of the vector.

You can do

v.erase(remove(v.begin(), v.end(), value), v.end());

which basically translates to "copy all the non-values towards the beginning
of the vector and erase the crud at the end".

So if you had a vector of int's, and there were 16 5's scattered over the
vector, then

v.erase(remove(v.begin(), v.end(), 5), v.end());

would make 1 pass over the vector, compacting all the non-5's and erasing 16
elements at the end.

Stephen Howe
 
B

Ben

Ben said:
vec.erase(iter);
where vec is your vector, and iter is an iterator to the object you
wish to remove.

--
Clark S. Cox, III
(e-mail address removed)

Or you can do vec.erase(vec.begin() + i) // where i is an integer
for the element #



Which is the same, an iterator to the object.

--
Ioannis Vranos


http://www23.brinkster.com/noi­cys



Yes, it is an iterator.
I just wanted to show laniik how to do an erase using the same index
that he was using in his step 1.

-Benjamin Dacko
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,592
Members
45,103
Latest member
VinaykumarnNevatia
Top