How to delete an element from a vector while looping over it?

前端 未结 6 2032
时光取名叫无心
时光取名叫无心 2020-11-27 17:41

I am looping through a vector with a loop such as for(int i = 0; i < vec.size(); i++). Within this loop, I check a condition on the element at that vector i

6条回答
  •  旧巷少年郎
    2020-11-27 18:19

    If you cannot use remove/erase (e.g. because you don't want to use lambdas or write a predicate), use the standard idiom for sequence container element removal:

    for (auto it = v.cbegin(); it != v.cend() /* not hoisted */; /* no increment */)
    {
        if (delete_condition)
        {
            it = v.erase(it);
        }
        else
        {
            ++it;
        }
    }
    

    If possible, though, prefer remove/erase:

    #include 
    
    v.erase(std::remove_if(v.begin(), v.end(),
                           [](T const & x) -> bool { /* decide */ }),
            v.end());
    

提交回复
热议问题