Home >Backend Development >C++ >Can You Remove Elements from a C Vector While Using a Range-Based For Loop?

Can You Remove Elements from a C Vector While Using a Range-Based For Loop?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 17:41:14935browse

Can You Remove Elements from a C   Vector While Using a Range-Based For Loop?

Iterating and Modifying Vectors with C 11 Range Loop

When looping through a vector using C 11's range-based for, a common question arises: can you remove an item while within the loop?

Limitations of Range-based For Loops

The answer is no, as range-based for loops are designed for accessing each element of a container a single time. If you need to modify the container, remove elements, or perform non-linear iterations, you should use a traditional for loop instead.

Modifying Vectors with Traditional Loops

To remove an item from a vector while iterating, you can use a traditional for loop:

for (auto it = inv.begin(); it != inv.end(); ++it) {
    // Do some stuff
    if (blah) {
        it = inv.erase(it);
        --it;  // Decrement iterator to avoid skipping an element
    }
}

Advantages of Traditional Loops

Traditional loops offer more flexibility than range-based for loops:

  • You can access elements multiple times.
  • You can modify the container by adding or removing elements.
  • You can iterate through the container in a non-linear fashion, such as skipping or revisiting elements.

The above is the detailed content of Can You Remove Elements from a C Vector While Using a Range-Based For Loop?. 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