Hello,
Say I have a vector of something called "vec" And I use this for loop to access the elements of vec
for(size_t i=0; i<vec.size(); i++)
{
}
How can I remove the element from the vector without an iterator?
Thanks!
Printable View
Hello,
Say I have a vector of something called "vec" And I use this for loop to access the elements of vec
for(size_t i=0; i<vec.size(); i++)
{
}
How can I remove the element from the vector without an iterator?
Thanks!
You can get an iterator from a vector's index by adding the index to the iterator returned by begin(). That said, have you considered using std::remove() or std::remove_if() with the version of erase() that takes iterators that denote a range? That approach is less error prone and likely to be faster.
Hello Laserlight..
So to remove I might do this:
vec.erase(vec.begin()+i); ?
Is that right??
Thanks!
Yes, but you need to be careful about the loop index variable "i"
if you erase an element.
when will this code not work then? I guess what you mean is that i will actually change right?
say I have these elements in the list: a a b c d
and I do an erase on b, which is index i=2 my code would look like this:
vec.erase(vec.begin()+i);
however, in my for loop if it continues it will next grab index=3 which is now d, skipping the element c.
Is that a correct analysis?
Thanks!
Yes, unless you make it such that you only increment the loop index when you do not erase anything. So, why not use std::remove() or std::remove_if()?
hey laser,
maybe I will look at those methods. I break form the loop when I find the element I want to erase, so the loop is not an issue.
Thanks though!!!
Iterators could be more flexible than an index as erase returns an iterator to the element after the last element erased.
In that case, use std::find() or std::find_if() with erase().Quote:
Originally Posted by lab1
Heya laser,
I would have done find() but the list is of sockaddr_in's and all I have is an ip address and a port. so I have to go through each sockaddr_in and compare those internal values.
Thanks though!
That is where std::find_if() would come in handy.Quote:
Originally Posted by lab1
Not exactly to original question but when removing elements from std::vector, always keep this in mind.