简体   繁体   English

具有迭代器的C ++模板函数

[英]C++ template function with iterators

I should implement a template function that goes over an iterator range checking whether a parameter predicate's condition is satisfied with the values, and the values which do not satisfy the predicate condition are copied to parameter output using the parameter insert iterator. 我应该实现一个遍历迭代器范围的模板函数,以检查参数谓词的条件是否满足该值,并且使用参数插入迭代器将不满足谓词条件的值复制到参数输出。

I have written a main program to test my template function implementation, which returns no errors but my university's test program won't compile with my template function implementation and gives the following error: 我已经编写了一个主程序来测试我的模板函数实现,该程序不会返回任何错误,但是我所在大学的测试程序无法与我的模板函数实现一起编译,并给出以下错误:

/usr/include/c++/4.4/debug/safe_iterator.h:272: error: no match for 'operator+=' in '((__gnu_debug::_Safe_iterator<std::__norm::_List_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::__debug::list<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >*)this)->__gnu_debug::_Safe_iterator<std::__norm::_List_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::__debug::list<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::_M_current += __n'¶

My implementation is: 我的实现是:

template <typename IteratorIn, typename IteratorOut, typename Predicate>
IteratorOut copyIfNot(IteratorIn begin, IteratorIn end, IteratorOut out, Predicate pred) {
    for (IteratorIn iter = begin; iter != end; iter++) {
        if (!pred(*iter)) {
            std::copy(iter, iter + 1, out);
        }
    }

    return out;
}

Can you hint me on where the error might lie? 您能提示我错误可能在哪里吗?

Apparently you are using your function with list::iterator , which is not a random access iterator and does not implement operator+ as you are using in iter + 1 . 显然,您正在使用带list::iterator ,该函数不是随机访问迭代器,并且不会像iter + 1所使用的那样实现operator+

You will have to make a copy and use operator++ on it: 您将必须进行复制并在其上使用operator++

auto itercopy = iter;
std::copy(iter, ++itercopy, out);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM