检查迭代器
checked iterator
我正在尝试测试Stroustrup的c++书中的"checked iterator"的例子。该代码有一个运行时错误:"列表迭代器不兼容"。
错误由函数"valid()
"的"if( c->end() == p )
"触发。这个错误意味着什么?我猜c->end()
和p
都应该是list<int>::iterator
类型。
另外,我不明白为什么"operator"是这样实现的。顺便说一句,我用的是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);
}
Checked_iter的构造函数应该接受Cont&,而不是Cont。您存储的是一个指向临时副本的指针。
相关文章:
- 检查迭代器是否具有我们要在C++中分配的值是否明智的优化
- enable_if检查迭代器的值类型是否为一对
- 为什么C++字符串迭代器不检查错误?
- 迭代器边界检查超出向量大小
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 检查容器模板类中的迭代器类型
- std::迭代器是否可以检查该迭代器上是否存在下一个元素?(此设计受到家庭作业的限制)
- 检查反向迭代器是否已越过正向迭代器
- 如何检查迭代器是否是C 中的output_iterator
- 迭代器unordered_map - 如何检查未初始化的元素
- 英特尔检查器 XE 2012 警告 #12367 - 将迭代器参数切片传递给 vector::erase()
- C 迭代器操作未检查溢出
- Visual Studio检查了迭代器不抛出异常
- 如何检查迭代器是否形成连续的内存区域
- 带范围检查的自制迭代器
- 给定同一数据结构的两个迭代器,如何检查哪个迭代器在另一个之前
- 如何检查是否可以推进简单C++标准库迭代器
- 检查对象之间的冲突时,列表迭代器不可递增
- 映射/集合迭代器不兼容-检查对象是否在映射中