Question: I want to do something like:

```
std::vector<Class*> myVector;
std::vector<Class*> tempvector;
// Fill myVector

for (std::vector<Class*>::iterator it = myVector.begin(); it != myVector.end(); ++it)
     if (some condition)
         tempvector.push_back(it*);

for (std::vector<Class*>::iterator it = tmpvector.begin(); it != tmpvector.end(); ++it)
     myVector.erase(it);

```

i.e., I fill myVector, then it is iterated and marks some elements for removal which are stored on a temporal vector, then the temporal vector is iterated and deletes the marked elements on myVector.

How can I do this? I need to mark the elements for later removal.

Answer: 
You need to loop from the last iterator to the first since when you erase an element in a vector all iterators past the one you deleted are invalidated.

```
std::vector<Class*> myVector;
std::vector<std::vector<Class*>::iterator> tempvector;
// Fill myVector

for (std::vector<Class*>::iterator it = myVector.begin(); it != myVector.end(); ++it)
     if (some condition)
         tempvector.push_back(it);

for (std::vector<std::vector<Class*>::iterator>::iterator it = tmpvector.end(); it != tmpvector.begin(); --it)
     myVector.erase(*it);

```
Try this, I changed `Class*` to `int` to make it simple to introduce the idea. I've mixed, [`.erase`](http://en.cppreference.com/w/cpp/container/vector/erase), [`std::remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) and [`std::find`](http://en.cppreference.com/w/cpp/algorithm/find) together:

```
std::vector<int> myVector;
std::vector<int> toRemove;

for (std::vector<int>::iterator it=myVector.begin(); it != myVector.end(); ++it)
    if (...condition...)
        toRemove.push_back(*it);

myVector.erase(std::remove_if(myVector.begin(), myVector.end(),
    [&toRemove](int x)
    {
        return std::find(toRemove.begin(), toRemove.end(), x) != toRemove.end();
    }), myVector.end());

```

or

```
for (std::vector<int>::iterator it=myVector.begin(); it!=myVector.end(); )
{
    if(std::find(toRemove.begin(), toRemove.end(), x) != toRemove.end()) 
      it = myVector.erase(it);
    else 
      ++it;
}

```