fork download
  1. #include <iostream>
  2. #include <set>
  3.  
  4. template<typename Cont, typename Pred>
  5. void bidir_remove_if( Cont &c, Pred p, bool forward )
  6. {
  7. auto b = c.begin();
  8. auto e = c.end();
  9. while( b != e ) {
  10. auto it = forward ? b++ : --e;
  11. if( p(*it) ) {
  12. auto end = b == e;
  13. ( forward ? it : e ) = c.erase( it );
  14. if( end ) break;
  15. }
  16. }
  17. }
  18.  
  19. int main()
  20. {
  21. std::set<int> s1 = { 1,2,3,4,5 };
  22. auto s2 = s1;
  23. auto p = []( int i ) {
  24. std::cout << i << " ";
  25. return i % 2;
  26. };
  27. bidir_remove_if( s1, p, true );
  28. std::cout << std::endl;
  29. for( int i : s1 ) std::cout << i << " ";
  30. std::cout << std::endl;
  31. bidir_remove_if( s2, p, false );
  32. std::cout << std::endl;
  33. for( int i : s2 ) std::cout << i << " ";
  34. std::cout << std::endl;
  35. }
  36.  
Success #stdin #stdout 0s 4532KB
stdin
Standard input is empty
stdout
1 2 3 4 5 
2 4 
5 4 3 2 1 
2 4