[英]checked iterator
I am trying to test the example of "checked iterator" from Stroustrup's C++ book. 我正在尝试从Stroustrup的C ++书中测试“检查迭代器”的示例。 The code has a run time error: "list iterators incompatible". 代码有一个运行时错误:“list iterators incompatible”。
The error is trigger by " if( c->end() == p )
" of function " valid()
". 该错误由函数“ valid()
”的“ if( c->end() == p )
”触发。 What does this error mean? 这个错误是什么意思? I guess both c->end()
and p
should be of type list<int>::iterator
. 我猜c->end()
和p
都应该是list<int>::iterator
。
In addition, I don't understand why "operator" was implemented in that way. 另外,我不明白为什么以这种方式实现“操作员”。 BTW, I am using VS2008. 顺便说一下,我正在使用VS2008。
struct out_of_bounds{
out_of_bounds() {}
};
template<class Cont, class Iter = typename Cont::iterator>
class Checked_iter : public iterator_traits<Iter> // deriving from iterator_traits
{
Iter curr; // iterator for current position
Cont* c; // pointer to current container
// ...
public:
void valid(Iter p){
if ( c->end() == p )
return;
for (Iter pp = c->begin(); pp != c->end(); ++pp ){
if ( pp == p )
return;
}
throw out_of_bounds();
}
friend bool operator==(const Checked_iter& i, const Checked_iter& j){
return i.c == j.c && i.curr == j.curr;
}
// no default initializer
// use default copy constructor and copy assignment
Checked_iter(Cont x, Iter p) : c(&x), curr(p) { valid(p); }
reference operator*(){
if ( curr == c->end() ) throw out_of_bounds();
return *curr;
}
pointer operator->(){
return &*curr; // checked by *
}
Checked_iter operator+(difference_type d){ // for random-access iterator only
if ( c->end() - curr <= d )
throw out_of_bounds();
return Checked_iter(c, curr+d);
}
reference operator[](difference_type d){ // for random-access iterator only
if ( c->end() - curr <= d ) throw out_of_bounds();
return c[d];
}
Checked_iter& operator++(){ // prefix ++
if ( curr == c->end() ) throw out_of_bounds();
++curr;
return *this;
}
Checked_iter& operator++(int) { // postfix ++
Checked_iter temp = *this;
++*this; // checked by prefix ++
return temp;
}
Checked_iter& operator--() { // prefix --
if ( curr == c->begin() ) throw out_of_bounds();
--curr;
return *this;
}
Checked_iter& operator--(int) { // postfix --
Checked_iter temp = *this;
--*this; // check by prefix
return temp;
}
difference_type index() { return curr-c.begin(); } // random-access only
Iter unchecked(){ return curr; }
};
void f2(list<int>& ls){
int count = 0;
try{
Checked_iter< list<int> > p(ls, ls.begin() );
while(true){
++p;
++count;
//cout << "element: " << *p << " count: " << count << endl;
}
}
catch(out_of_bounds){
cout << "overrun after " << count << " tries \n";
}
}
void test9(){
int a[] = {0,1,2,3,4,5,6,7,8,9};
list<int> l(a, a+sizeof(a)/sizeof(int));
show(l);
f2(l);
}
The constructor for Checked_iter should take Cont&, not Cont. Checked_iter的构造函数应采用Cont&,而不是Cont。 You are storing a pointer to a temporary copy. 您正在存储指向临时副本的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.