虽然 remove_if 对一元谓词进行操作,但将其扩展到任何其他 n 参数谓词并不困难。
例如 remove with binary predicate 可以这样写:
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;
}
但是您必须根据自己的需要来调整它。这完全取决于您如何处理成对的元素,如果谓词返回 true 或其中一个,您是否要删除它们?只有左边还是只有右边?等等……
用法:
#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, a + 11);
std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, ","));
std::cout << std::endl;
std::vector<int>::iterator it = 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;
}
输出:
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
如果条件成立,此版本会删除这两个元素。
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,