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
Release: 2024-11-28 17:41:14
Original
944 people have browsed it

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

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!

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