I have an std::vector<Bullet> bullets and in the for-loop below I want to remove a bullet from the vector if it's not alive anymore.
My plan is to remove the element with pop_back(). If there are more than one element in the vector I want to first swap the element that is to be removed with the last element in the vector, and then call pop_back().
for (std::vector<Bullet>::iterator b = bullets.begin(); b != bullets.end(); ++b) { if(!b->isAlive()) { if (bullets.size() > 1) { std::iter_swap(bullets + ..., bullets.end()); } bullets.pop_back(); } } The problem is the first parameter in iter_swap. I looked up http://www.cplusplus.com/reference/algorithm/iter_swap/ and the syntax for the first parameter is the vector + the position of the element.
How do I find out b's index in the vector?
b.b - bullets.begin()would give the index.forloop takes linear time. Remove-erase is swap-and-pop.iter_swap(b, bullets.end() - 1)(emphasis on "- 1")?