Remove elements of a vector inside the loop

You should not increment it in the for loop: for (vector<Player>::iterator it=allPlayers.begin(); it!=allPlayers.end(); /*it++*/) <———– I commented it. { if(it->getpMoney()<=0) it = allPlayers.erase(it); else ++it; } Notice the commented part;it++ is not needed there, as it is getting incremented in the for-body itself. As for the error “‘operator=” function is unavailable in “Player’“, it comes … Read more

How do I erase an element from std::vector by index?

To delete a single element, you could do: std::vector<int> vec; vec.push_back(6); vec.push_back(-17); vec.push_back(12); // Deletes the second element (vec[1]) vec.erase(std::next(vec.begin())); Or, to delete more than one element at once: // Deletes the second through third elements (vec[1], vec[2]) vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3));

Erasing elements from a vector

Use the remove/erase idiom: std::vector<int>& vec = myNumbers; // use shorter name vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); What happens is that remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements … Read more

tech