Home >Backend Development >C++ >How to Safely Remove Elements from a Vector During Loop Iteration in C ?

How to Safely Remove Elements from a Vector During Loop Iteration in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 14:45:13926browse

How to Safely Remove Elements from a Vector During Loop Iteration in C  ?

Removing Elements from a Vector Within a Loop

It is essential to know how to remove elements from a vector effectively during loop iterations. Attempting to do so using the following code may result in an error:

for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); it++)
{
    if(it->getpMoney() <= 0)
        it = allPlayers.erase(it);
    else
        ++it;
}

The error message, "operator '=' function is unavailable in 'Player'", indicates that the objects in the vector cannot be directly reassigned. To resolve this, the Player class must implement the assignment operator (=).

Additionally, the for loop should be modified to avoid incrementing the iterator explicitly, as this is already handled internally:

for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); )
{
    if(it->getpMoney() <= 0)
        it = allPlayers.erase(it);
    else
        ++it;
}

Instead of using a raw loop, it is recommended to leverage the Erase-Remove Idiom for greater efficiency:

allPlayers.erase(
    std::remove_if(
        allPlayers.begin(),
        allPlayers.end(),
        [](Player const &amp; p) { return p.getpMoney() <= 0; }
    ),
    allPlayers.end()
);

This idiom uses the remove_if algorithm to filter out the elements that meet the specified condition (players with zero or negative money in this case) and then uses the erase function to remove them from the vector.

The above is the detailed content of How to Safely Remove Elements from a Vector During Loop Iteration in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn