Deleting elements out of a vector

  • Thread starter Christian Bruckhoff
  • Start date
C

Christian Bruckhoff

Hi.

Is there a possibility to delete elements out of a vector?
At the moment i do it by copying all needed elements to another vector.
After clearing the old vector i copy them back element by element.

Regards!
Christian
 
D

Daniel T.

"Christian Bruckhoff said:
Hi.

Is there a possibility to delete elements out of a vector?
At the moment i do it by copying all needed elements to another vector.
After clearing the old vector i copy them back element by element.

All sequences, including std::vector have an 'erase' member-function.

a.erase(p)

p is a dereferenceable iterator in a.

Destroys the element pointed to by p and removes it from a.

a.size() is decremented by 1. The relative order of the other elements
in the sequence is unchanged. The return value is an iterator to the
element immediately following the one that was erased.

Warning: there is no guarantee that a valid iterator on a is still valid
after an insertion or an erasure. In some cases iterators do remain
valid, and in other cases they do not. The details are different for
each sequence class.
 
J

Jerry Coffin

Hi.

Is there a possibility to delete elements out of a vector?

Yes. vector::erase can do that.
At the moment i do it by copying all needed elements to another vector.
After clearing the old vector i copy them back element by element.

The usual way is to use std::remove_if, which, contrary to its name
doesn't really remove anything -- it just rearranges the elements so
those to be kept are together at the beginning of the vector (or
whatever collection you're using). You can then use vector::erase to
erase the elements at the end that you don't want anymore.
 
G

Greg

Jerry said:
Yes. vector::erase can do that.


The usual way is to use std::remove_if, which, contrary to its name
doesn't really remove anything -- it just rearranges the elements so
those to be kept are together at the beginning of the vector (or
whatever collection you're using). You can then use vector::erase to
erase the elements at the end that you don't want anymore.

To remove items by value, std::remove() would be a better choice than
std::remove_if(). Also some sample code illustrating this technique
might be helpful:

#include <vector>
#include <algorithm>

int main()
{
std::vector<int> v;

v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(5);

v.erase( remove( v.begin(), v.end(), 1), v.end());
}

would erase all the "1"'s from the vector v.

Greg
 

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,772
Messages
2,569,593
Members
45,113
Latest member
Vinay KumarNevatia
Top