Home > Backend Development > C++ > Can We Remove Elements from a Vector Inside a C 11 Range-Based For Loop?

Can We Remove Elements from a Vector Inside a C 11 Range-Based For Loop?

Barbara Streisand
Release: 2024-12-06 01:32:09
Original
886 people have browsed it

Can We Remove Elements from a Vector Inside a C  11 Range-Based For Loop?

Removing Elements from Vectors in C 11 Range-Based Loops

In C 11, range-based for loops offer a convenient way to iterate through container elements. However, removing elements from the container within these loops poses a challenge.

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
    // I need to remove this object from 'inv'...
}
Copy after login

Can We Remove Elements Within Range-Based Loops?

No, you cannot remove elements from a vector within a range-based for loop. This is because the loop operates by creating a copy of the vector iterator, which becomes invalidated if elements are removed or added.

Therefore, it is crucial to consider alternative approaches for modifying containers during iteration.

Recommended Solution

The recommended approach is to use the traditional for loop or one of its variants. This allows you to directly manipulate the vector and remove elements as needed. For example:

auto i = std::begin(inv);

while (i != std::end(inv)) {
    // Do some stuff
    if (blah)
        i = inv.erase(i);
    else
        ++i;
}
Copy after login

The above is the detailed content of Can We Remove Elements from a Vector Inside a C 11 Range-Based For 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