rize
rize

Reputation: 859

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?

Upvotes: 1

Views: 951

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75150

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);

Upvotes: 1

Related Questions