c++ - Iterator range erase element -


is possible erase elements iterator_range?

something (unfortunately code not work):

void test_erase(my_it it,my_it end){ boost::iterator_range<my_it> r(it,end);  for(; it<end; it++){     if(pred(my_it)){         boost::erase(r,boost::iterator_range<my_it>(it,it));         continue;     } } 

pred checks value of my_it , of (my_it+1)

the point rid of constructing objects vector, map or string

although remove_if operates on unary predicate not difficult extend on other n arguments predicate.

for example remove binary predicate can written way:

template<class forwardit, class binarypredicate> forwardit removeif(forwardit first, forwardit last, binarypredicate p) {      forwardit result = first;     while ( first != last - 1) {         if ( !p( *first, *( first + 1))) {             *result = *first;             ++result;         }         if( first == last - 1) return result;         ++first;     }     return result; } 

but have fit needs. depends how treat pairs of elements, want remove both of them if predicate returns true or 1 of them? left or right? etc...

usage:

#include <iostream> #include <vector> #include <algorithm> #include <iterator>  bool bp (int left, int right) { return ( left + right == 2); } /*  *   */ int main(int argc, char** argv) {      int a[] = { 0, 2, 1, 3, 0, 2, 3, 2, 0, 3, 8};     std::vector<int> v( a, + 11);     std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, ","));     std::cout << std::endl;     std::vector<int>::iterator = removeif( v.begin(), v.end(), bp);     std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, ","));     v.erase( it, v.end()); std::cout << std::endl;     std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, ","));     return 0; } 

output:

0,2,1,3,0,2,3,2,0,3,8,

2,1,3,2,3,0,3,2,0,3,8,

2,1,3,2,3,0,3,

http://ideone.com/8bcmjq


this version removes both elements if condition holds.

template<class forwardit, class binarypredicate> forwardit removeif(forwardit first, forwardit last, binarypredicate p) {      forwardit result = first;     while (first != last - 1) {         if (!p(*first, *(first + 1))) {             *result++ = *first++;             *result++ = *first++;         } else {             if (first == last - 1) return result;             ++first;             ++first;         }     }     return result; } 

0,2,1,3,0,2,3,2,0,3,8,

1,3,3,2,0,3,3,2,0,3,8,

1,3,3,2,0,3,


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -