Removing Elements from a Vector Inside a Loop
While iterating through a vector using a for loop, a common task is to remove elements based on specific criteria. However, attempting to remove an element within the loop itself can lead to errors.
Consider the following code:
for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); it++) { if(it->getpMoney() <= 0) it = allPlayers.erase(it); else ++it; }
This code attempts to remove players with negative or zero money from the vector allPlayers. However, it results in the error message:
'operator =' function is unavailable in 'Player'
The Problem
The error arises because the erase() method internally utilizes the assignment operator = to move elements within the vector. To use erase(), the Player objects must be assignable, requiring an implementation of the operator= for the Player class.
The Solution
To resolve the issue, avoid incrementing it within the for loop:
for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); /*it++*/) { if(it->getpMoney() <= 0) it = allPlayers.erase(it); }
Implement the operator= for the Player class to enable assigning objects within the vector.
Alternative Approach Using Algorithms
To simplify the code, consider using the Erase-Remove Idiom:
allPlayers.erase( std::remove_if( allPlayers.begin(), allPlayers.end(), [](Player const & p) { return p.getpMoney() <= 0; } ), allPlayers.end() );
This code employs the std::remove_if() algorithm to filter out players with negative or zero money, and then uses erase() to remove them from the vector.
The above is the detailed content of How to Safely Remove Elements from a Vector While Iterating in C ?. For more information, please follow other related articles on the PHP Chinese website!