Erasing vector::end from vector

The standard doesn’t quite spell it out, but v.erase(q) is defined, “Erases the element pointed to by q” in [sequence.reqmts]. This means that q must actually point to an element, which the end iterator doesn’t. Passing in the end iterator is undefined behavior. Unfortunately, you need to write: auto it = std::find(…); if (it != … Read more

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