int greater6 ( int value ) { return value >6; } int _tmain(int argc, _TCHAR* argv[]) { int Array[12] = {1,7,9,2,0,7,7,3,4,6,8,5}; vector <int> v1; vector <int>::iterator Iter1, Iter2, new_end; for(int i=0;i<12;i++) v1.push_back(Array[i]); cout << "Vector v1 is \n( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; new_end = remove_if (v1.begin( ), v1.end( ), greater6 ); cout << "Vector v1 with elements satisfying greater6 removed is\n( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; // To change the sequence size, use erase v1.erase (new_end, v1.end( ) ); cout << "Vector v1 resized elements satisfying greater6 removed is\n( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")." << endl; }
下面是伪代码:
remove_if(itr_begin,itr_end,funPtr) { itr_find = find_if(itr_begin,itr_end,funPtr); itr_begin = itr_find; unchecked_remove_copy_if(++itr_begin,itr_end,itr_begin,funPtr); }
remove_copy_if(_First,_Last,_Dest,funPtr) { for (; _First != _Last; ++_First) { if (!funPtr(*_First)) *_Dest++ = *_First; } return (_Dest); }
(貌似排版有点问题,在执行第一次循环的时候迭代器d是指向元素7,f指向元素9)
1 1, 7, 9, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 2 1, 2, 9, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 3 1, 2, 0, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 4 1, 2, 0, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 5 1, 2, 0, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 6 1, 2, 0, 2, 0, 7, 7, 3, 4, 6, 8, 5 end d f 7 1, 2, 0, 3, 0, 7, 7, 3, 4, 6, 8, 5 end d f 8 1, 2, 0, 3, 4, 7, 7, 3, 4, 6, 8, 5 end d f 9 1, 2, 0, 3, 4, 6, 7, 3, 4, 6, 8, 5 end d f 10 1, 2, 0, 3, 4, 6, 7, 3, 4, 6, 8, 5 end d f 11 1, 2, 0, 3, 4, 6, 5, 3, 4, 6, 8, 5 end d f
和remove_if算法类似的函数还有:
remove 方法第三个参数传入的是一个常量,表示移除指定的这个常量值
remove_copy_if 方法可以把移除后的结果通过第三个参数传入到另外一个的容器中,当然这个容器一定要足够大容纳下来容纳下元素,否则后果很严重。