Home >Backend Development >C++ >How to Safely Remove Elements from a Vector in a C Loop?
Deleting Elements from a Vector within a Loop
One common task when working with vectors is to remove specific elements based on their attributes. However, updating the vector while iterating through it can lead to unexpected errors.
Let's consider the following code snippet:
for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); it++) { if (it->getpMoney() <= 0) it = allPlayers.erase(it); else ++it; }
This code aims to remove players with zero or less money from the allPlayers vector. However, executing this code often results in the error message:
'operator =' function is unavailable in 'Player’
Cause of the Error:
The error occurs because std::vector::erase internally uses the assignment operator (=) to move elements within the vector. To use erase, the Player class must implement the assignment operator.
Solution without Assignment Operator:
To avoid the assignment operator requirement, comment out the it line in the loop:
for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); /*it++*/) { if (it->getpMoney() <= 0) it = allPlayers.erase(it); }
By removing the it increment, the iterator automatically advances after each erase operation.
Refactoring using Erase-Remove Idiom:
A cleaner solution is to use the Erase-Remove Idiom, which provides a concise and efficient way to remove elements from a vector:
allPlayers.erase( std::remove_if( allPlayers.begin(), allPlayers.end(), [](Player const & p) { return p.getpMoney() <= 0; } ), allPlayers.end() );
In this approach, std::remove_if filters the vector based on the provided lambda expression. The filtered elements are then removed using std::vector::erase.
The above is the detailed content of How to Safely Remove Elements from a Vector in a C Loop?. For more information, please follow other related articles on the PHP Chinese website!