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

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

Mary-Kate Olsen
Release: 2024-12-10 03:55:21
Original
1041 people have browsed it

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;
}
Copy after login

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);
}
Copy after login

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()
);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template