c++ - 迭代器范围删除元素

标签 c++ algorithm boost stl iterator

是否可以从 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) 的值

重点是摆脱构造对象,如 vectormapstring

最佳答案

尽管 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,

关于c++ - 迭代器范围删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291332/

相关文章:

C++11 std::async 回调

c++ - 将多个 .txt 文件读入一个 vector<double>

algorithm - 彼得森的算法是否满足饥饿?

c++ - 清除包括换行符的输入缓冲区

c++ - boost 范围 weak_ptr

c++ - Lambda 中数组衰减为指针

c++ - 指向64位数字中的32位是否安全?

c++ - 家谱的数据结构

c++ - 计算无向图中的度数 - 逻辑问题

c++ - 独立 DLL 之间的内部进程通信