【发布时间】:2017-04-23 23:20:49
【问题描述】:
当我在 std::find() 中传递用户定义的迭代器参数时,GCC 5.2.1.编译器(在 Ubuntu 15.10 上)给出了两条错误消息:
(1)
/usr/include/c++/5/bits/stl_algo.h:162:34:错误:没有匹配 调用“__iterator_category(Text_iterator&)”的函数
std::__iterator_category(__first));
(2)
/usr/include/c++/5/bits/stl_iterator_base_types.h:204:5:错误:否 “struct std::iterator_traits”中名为“iterator_category”的类型
错误是由 find_txt() 函数内部的auto p = find(first, last, first_char); 行引起的。当该行被注释掉时,代码会无缝编译。以下是导致错误的代码摘录:
#include "std_lib_facilities.h"//from B. Stroustrup's site
using Line = vector<char>;
class Text_iterator {
list<Line>::iterator ln; //points to lines
Line::iterator pos; //points to characters
public:
Text_iterator(list<Line>::iterator ll, Line::iterator pp)
:ln{ll}, pos{pp} { }
char& operator*() { return *pos; }
Text_iterator& operator++();
bool operator==(const Text_iterator& other) const
{ return ln==other.ln && pos==other.pos; }
bool operator!=(const Text_iterator& other) const
{ return !(*this==other); }
};
Text_iterator& Text_iterator::operator++()
{
++pos;
if (pos==(*ln).end()) {
++ln;
pos = (*ln).begin();
}
return *this;
}
Text_iterator find_txt(Text_iterator first, Text_iterator last, const string& s)
{
if (s.size()==0) return last;// can’t find an empty stringchar first_char = s[0];
char first_char = s[0];
while (true) {
auto p = find(first, last, first_char); //<------------the PROBLEM!!!!!!
//if (p==last || match(p,last,s)) return p;
//first = ++p;// look at the next character
}
}
void ex6()
{
;
}
int main()
{
ex6();
}
我参考了错误消息中提到的文件:
template<typename _Iterator, typename _Predicate>
inline _Iterator
__find_if(_Iterator __first, _Iterator __last, _Predicate __pred)
{
return __find_if(__first, __last, __pred,
std::__iterator_category(__first)); //this is line #162 in stl_algo.h
}
和
template<typename _Iter>
inline typename iterator_traits<_Iter>::iterator_category
__iterator_category(const _Iter&)//this is line #204 in stl_iterator_base_types.h
{ return typename iterator_traits<_Iter>::iterator_category(); }
问题出在auto p = find(first, last, first_char); 还是这两个GCC 库文件——即stl_algo.h 和stl_iterator_base_types.h?有哪些可能的处理方法?
我正在为 Stroustrup 的Programming: Principles and Practice Using C++第 2 版第 20 章的练习 6 准备代码。并被困在这里。在 Internet 上搜索 std::find() 问题无济于事。没有一个问题涉及此函数的迭代器参数。
【问题讨论】:
-
TL;DR:您的
Text_iterator不会因为您这样命名就成为迭代器。它不满足标准对迭代器的要求。
标签: c++ templates stl iterator