back_insert_iterator 与remove_copy_if
我试图将 back_insert_iterator
与使用向量的 remove_copy_if
一起使用,但出现编译错误。
你知道为什么下面的代码是错误的吗?
#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 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
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::remove_copy_if()
返回与输出迭代器类型相同的迭代器。在本例中,它是一个std::back_inserter_iterator
。您没有更改输入容器,而是将谓词不包含的元素复制到输出容器中。简而言之,如果您想更改输入容器,请使用 std::remove_if() 。
std::remove_copy_if()
returns an iterator of the same type as the output iterator. In this case, it's astd::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.