簡體   English   中英

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

[英]C++ template function with iterators

我應該實現一個遍歷迭代器范圍的模板函數,以檢查參數謂詞的條件是否滿足該值,並且使用參數插入迭代器將不滿足謂詞條件的值復制到參數輸出。

我已經編寫了一個主程序來測試我的模板函數實現,該程序不會返回任何錯誤,但是我所在大學的測試程序無法與我的模板函數實現一起編譯,並給出以下錯誤:

/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'¶

我的實現是:

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

您能提示我錯誤可能在哪里嗎?

顯然,您正在使用帶list::iterator ,該函數不是隨機訪問迭代器,並且不會像iter + 1所使用的那樣實現operator+

您將必須進行復制並在其上使用operator++

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM