【问题标题】:C++ template function with iterators带有迭代器的 C++ 模板函数
【发布时间】:2012-10-14 23:16:50
【问题描述】:

我应该实现一个模板函数,它会越过迭代器范围检查参数谓词的条件是否满足值,并且使用参数插入迭代器将不满足谓词条件的值复制到参数输出。

我编写了一个主程序来测试我的模板函数实现,它没有返回错误,但我大学的测试程序无法与我的模板函数实现一起编译并给出以下错误:

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

你能提示我错误可能在哪里吗?

【问题讨论】:

  • 不要使用 copy 只复制一个元素。更好的是:*out = *iter; ++out;。为什么错误 - 已经提供了很好的答案。

标签: c++ templates iterator


【解决方案1】:

显然您将函数与list::iterator 一起使用,它不是随机访问迭代器,也没有像您在iter + 1 中使用的那样实现operator+

您必须复制并在上面使用operator++

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

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2013-03-13
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    相关资源
    最近更新 更多