0

I want to pass a lambda function to for_each that captures a vector and delete all the elements that less than 10, it works partially but still showing elements that less than 10.

can anyone know what's wrong with it? the below code shows (10 8 5 6 4 77 15)

#include<iostream>
#include<vector>
#include<algorithm>
int main(){

    std::vector<int>vec{10,3,8,2,5,9,6,7,4,1,77,15};
    std::for_each(vec.begin(),vec.end(),[&vec](int x){if(x<10) vec.erase(remove(vec.begin(),vec.end(),x),vec.end());});
    for(auto&i:vec)
    std::cout<<i<<'\t';
 
    return 0;
}
  • 2
    Why not use `remove_if`/`erase`? – Stephen Newell Jun 13 '22 at 16:48
  • 3
    The `erase` in the lambda invalidates the iterators of the `for_each` ... Why not use `remove_if`? – ChrisMM Jun 13 '22 at 16:48
  • 3
    Modifying a vector while looping over it via iterators is a recipe for disaster. – aschepler Jun 13 '22 at 16:48
  • 1
    @StephenNewell OP is asking why a piece of code isn't working. A duplicate target that shows how to write a piece of code that sidesteps the OP's problem isn't really a duplicate. – cigien Jun 13 '22 at 16:51
  • 1
    I added a duplicate that I believe more directly answers the question "What's wrong with it?" – Drew Dormann Jun 13 '22 at 16:53
  • 1
    @DrewDormann Yeah, that's much closer, thanks. – cigien Jun 13 '22 at 16:56
  • @DrewDormann it is clear for me now thanks, for_each was not meant for modifications – Zerocool_m12 Jun 13 '22 at 16:58
  • @Zerocool_m12 If the compiler supports C++ 20 then just write std::erase_if( vec, []( const auto &item ) { return item < 10; } ); – Vlad from Moscow Jun 13 '22 at 17:00
  • 1
    @aschepler "*Modifying a vector while looping over it via iterators is a recipe for disaster*" - only if you don't manage the iterators correctly (as is the case here). For instance, this will work fine: `auto it = vec.begin(); while (it != vec.end()) { if (*it < 10){ it = vec.erase(it); } else { ++it; } }`. But I agree that using `remove_if()`+`erase()` or `erase_if()` would be better. – Remy Lebeau Jun 13 '22 at 19:39

0 Answers0