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

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

Barbara Streisand
Release: 2024-12-04 04:09:13
Original
180 people have browsed it

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

Remove Elements from a Vector Within a Loop

When iterating through a vector, there may be scenarios where you need to remove elements based on certain criteria. However, attempting to modify the vector while iterating can lead to runtime errors.

Consider the following scenario:

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 intends to remove players with zero or negative money. However, it fails with an error related to the assignment operator. To resolve this issue, avoid incrementing the iterator within the loop. Instead, rely on the iterator returned by the erase() function.

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

Furthermore, the use of operator= by the erase() function requires the Player class to be assignable, meaning the Player class must implement an assignment operator.

Erase-Remove Idiom for Vector Manipulation

To simplify the task of removing elements from a vector, embrace the Erase-Remove Idiom:

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

This idiom combines the remove_if() algorithm to identify the elements to erase and the erase() method to remove the required range.

The above is the detailed content of How to Safely Remove Elements from a Vector During Iteration in C ?. 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