how to erase from vector in range-based loop?

前端 未结 3 1835
我在风中等你
我在风中等你 2021-02-05 22:30

I simply wanna erase the specified element in the range-based loop:

vector vec = { 3, 4, 5, 6, 7, 8 };
for (auto & i:vec)
{
    if (i>5)
    ve         


        
相关标签:
3条回答
  • 2021-02-05 22:36

    It's quite simple: don't use a range-based loop. These loops are intended as a concise form for sequentially iterating over all the values in a container. If you want something more complicated (such as erasing or generally access to iterators), do it the explicit way:

    for (auto it = begin(vec); it != end(vec);) {
      if (*it > 5)
        it = vec.erase(it);
      else
        ++it;
    }
    
    0 讨论(0)
  • 2021-02-05 22:41

    Removing elements from a vector that you're iterating over is generally a bad idea. In your case you're most likely skipping the 7. A much better way would be using std::remove_if for it:

    vec.erase(std::remove_if(vec.begin(), vec.end(),
                              [](const int& i){ return i > 5; }),
               vec.end());
    

    std::remove shift the elements that should be removed to the end of the container and returns an iterator to the first of those elements. You only got to erase those elements up to the end then.

    0 讨论(0)
  • 2021-02-05 22:49

    You can't erase elements by value on a std::vector, and since range-based loop expose directly values your code doesn't make sense (vec.erase(&i)).

    The main problem is that a std::vector invalidates its iterators when you erase an element.

    So since the range-based loop is basically implemented as

    auto begin = vec.begin();
    auto end = vec.end()
    for (auto it = begin; it != end; ++it) {
      ..
    }
    

    Then erasing a value would invalidate it and break the successive iterations.

    If you really want to remove an element while iterating you must take care of updating the iterator correctly:

    for (auto it = vec.begin(); it != vec.end(); /* NOTHING */)
    {
      if ((*it) > 5)
        it = vec.erase(it);
      else
        ++it;
    }  
    
    0 讨论(0)
提交回复
热议问题