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

How to Safely Remove Elements from a Vector While Iterating in C 11?

Mary-Kate Olsen
Release: 2024-11-28 20:56:11
Original
371 people have browsed it

How to Safely Remove Elements from a Vector While Iterating in C  11?

Removing Elements from Vectors During C 11 Range-Based Loops

Range-based for loops in C 11 provide a convenient way to iterate over the elements of a container, especially when you need to perform actions on each element. However, when dealing with vectors, you may sometimes need to remove elements from the vector while iterating over it.

Problem

Consider the following code:

std::vector<IInventory*> inv;
inv.push_back(new Foo());
inv.push_back(new Bar());

for (IInventory* index : inv)
{
    // Do some stuff
    // ...
}
Copy after login

Inside the loop, you realize that you need to remove a particular element from the vector inv. However, you encounter two issues:

  1. Cannot Remove Element: The range-based for loop does not provide a way to modify the vector while iterating over it.
  2. Loop Validity: Removing an element from a vector can potentially invalidate the loop.

Solution

Range-based for loops are intended for situations where you need to access each element of the container only once. If you need to modify or remove elements during iteration, you should use a traditional for loop or one of its iterator-based variations.

Here's how you can modify the code using a traditional for loop with iterator increment management:

for (auto i = inv.begin(); i != inv.end(); /*++i*/) {
    // Do stuff
    if (should_remove) {
        i = inv.erase(i);
    } else {
        ++i;
    }
}
Copy after login

By explicitly managing the iterator increment, you maintain the validity of the loop and ensure that you can remove and modify elements without encountering any errors.

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