back_insert_iterator with remove_copy_if
I am trying to use a back_insert_iterator
with remove_copy_if
using vectors but I have compile errors.
Do you know why the code below is wrong?
#include <iostream>
#include <string>
#include <algorithm>
#include <cassert>
#include <vector>
#include <iterator>
#include <functional>
struct checkRem : std::unary_function<int,bool> {
int _val;
checkRem( int val ): _val(val){}
bool operator()(int aVal){ return aVal > _val;}
};
int main( int开发者_C百科 argc, char** argv )
{
int _vIn[] = {1,2,3,4,2,3,4,3,6,7};
std::vector< int > vIn( _vIn, _vIn + (sizeof( _vIn )/sizeof(_vIn[0])));
// remove with copy
std::vector<int>vOut;
std::back_insert_iterator< std::vector<int> > bit( vOut );
std::vector< int >::iterator new_end =
std::remove_copy_if(
vIn.begin(),
vIn.end(),
bit,
checkRem(2)
);
}
back_insrt_iter.cpp: In function ‘int main(int, char**)’:
back_insrt_iter.cpp:30: error: conversion from
‘std::back_insert_iterator<std::vector<int, std::allocator<int> > >’ to non-scalar
type ‘__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >’
requested
std::remove_copy_if()
returns an iterator of the same type as the output iterator. In this case, it's a std::back_inserter_iterator
. You're not changing the input container, but you're copying into an output container the elements for which the predicate doesn't hold.
In short, use std::remove_if()
if you want to change your input container.
精彩评论