How can you erase elements from a vector while iterating?

Since C++20, there are freestanding std::erase and std::erase_if functions that work on containers and simplify things considerably: std::erase(myNumbers, number_in); // or std::erase_if(myNumbers, [&](int x) { return x == number_in; }); Prior to C++20, use the erase-remove idiom: std::vector<int>& vec = myNumbers; // use shorter name vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); // or vec.erase(std::remove_if(vec.begin(), vec.end(), [&](int x) … Read more

c++ stl what does base() do

base() converts a reverse iterator into the corresponding forward iterator. However, despite its simplicity, this correspondence is not as trivial as one might thing. When a reverse iterator points at one element, it dereferences the previous one, so the element it physically points to and the element it logically points to are different. In the … Read more

Erase whole array Python

Note that list and array are different classes. You can do: del mylist[:] This will actually modify your existing list. David’s answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?). Try: a = … Read more

unlink vs remove in c++

Apart from the fact that unlink is unix-specific (as pointed out by Chris), we read in the POSIX manual: If path does not name a directory, remove(path) is equivalent to unlink(path). If path names a directory, remove(path) is equivalent to rmdir(path). As for the directory-passed unlink, we read: The path argument must not name a … 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

tech