是否可以从 iterator_range 中删除元素?
类似这样的事情(不幸的是这段代码不起作用):
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 检查 my_it 和 (my_it+1) 的值
重点是摆脱构造对象,如 vector
、map
或 string
最佳答案
尽管 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,
如果条件成立,此版本会删除这两个元素。
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,
关于c++ - 迭代器范围删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291332/