简体   繁体   中英

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 .

You will have to make a copy and use operator++ on it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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