back_insert_iterator 与remove_copy_if

发布于 2024-09-29 00:47:18 字数 1220 浏览 3 评论 0原文

我试图将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转瞬即逝 2024-10-06 00:47:18

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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文