无法使用自定义迭代器获取std::find_if进行编译

Unable to get std::find_if to compile with custom iterator

本文关键字:find if 编译 std 自定义 获取 迭代器      更新时间:2023-10-16

这是导致问题的行:

auto it = find_if(menus->begin(), menus->end(), [](MenuComponent* m){return true;});

我的迭代器定义为:

class ComponentIterator : std::iterator< std::forward_iterator_tag, MenuComponent* > 

定义了++, ==, !=, *, ->。该迭代器也适用于以下行:

auto it = copy_if(menus->begin(), menus->end(), othermenu.begin(), [](MenuComponent* m){return true;});

g++ 4.8.1输出如下:

In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from main.cpp:2:
/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of ‘_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = ComponentIterator; _Predicate = main()::__lambda0]’:
main.cpp:211:97:   required from here
/usr/include/c++/4.8/bits/stl_algo.h:4465:40: error: no matching function for call to ‘__iterator_category(ComponentIterator&)’
        std::__iterator_category(__first));
                                        ^
/usr/include/c++/4.8/bits/stl_algo.h:4465:40: note: candidate is:
In file included from /usr/include/c++/4.8/bits/stl_algobase.h:65:0,
                 from /usr/include/c++/4.8/bits/char_traits.h:39,
                 from /usr/include/c++/4.8/string:40,
                 from main.cpp:1:
/usr/include/c++/4.8/bits/stl_iterator_base_types.h:201:5: note: template<class _Iter> typename std::iterator_traits<_Iterator>::iterator_category std::__iterator_category(const _Iter&)
     __iterator_category(const _Iter&)
     ^
/usr/include/c++/4.8/bits/stl_iterator_base_types.h:201:5: note:   template argument deduction/substitution failed:
/usr/include/c++/4.8/bits/stl_iterator_base_types.h: In substitution of ‘template<class _Iter> typename std::iterator_traits<_Iterator>::iterator_category std::__iterator_category(const _Iter&) [with _Iter = ComponentIterator]’:
/usr/include/c++/4.8/bits/stl_algo.h:4465:40:   required from ‘_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = ComponentIterator; _Predicate = main()::__lambda0]’
main.cpp:211:97:   required from here
/usr/include/c++/4.8/bits/stl_iterator_base_types.h:201:5: error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<ComponentIterator>’
make: *** [main.o] Error 1

任何想法?

最可能的原因是class ComponentIterator : blah blah的继承是私有的。

就像Loki在评论中说的那样,如果没有一个可用的例子来确认切换到public是否解决了问题,很难确定。