这是我必须为学校解决的练习,所以请不要给我完整的解决方案,只是提示 ;-)
练习如下:
- 实现一个封装另一个迭代器(即序列)并执行范围检查的迭代器
- 迭代器用序列的第一个和最后一个元素初始化
- 如果迭代器指向第一个元素并递减,或者如果迭代器指向最后一个元素并递增,则发出错误信号——选择一种适当的错误信号形式
首先我想继承 vector 容器的迭代器,然后我得到了这个(只是我的“解决方案”的一部分,但我意识到这很糟糕并且停止了......):
template <typename T>
class myIter : std::vector<T>::iterator
{
public:
myIter( typename std::vector<T>::iterator start,
typename std::vector<T>::iterator end,
typename std::vector<T>::iterator pos,
bool behaviour=false) : s(start), e(end), p(pos), beh(behaviour)
{overflowFlag = false;};
typename std::vector<T>::iterator & operator++();
typename std::vector<T>::iterator & operator--();
typename std::vector<T>::iterator operator++(int);
typename std::vector<T>::iterator operator--(int);
typename std::vector<T>::iterator & operator+=(int);
typename std::vector<T>::iterator & operator-=(int);
typename std::vector<T>::iterator operator+(int);
typename std::vector<T>::iterator operator-(int);
myIter & operator=(const myIter&) = delete;
T operator*(){ return *p;};
bool getFlag() {return overflowFlag;};
private:
typename std::vector<T>::iterator s, e, p;
bool beh;
bool overflowFlag; // is set if beh = false. otherwise exception;
};
所以我意识到我并没有真正继承 vector 迭代器(我继承了 vector 迭代器,但我没有使用它)。使用标准迭代器功能的最简单方法是什么,但在“顶部”实现范围检查?如果超出范围,我可以抛出异常或设置一个“errorflag”(由 bool 值“beh”指定),但这应该不是实现的问题。
最佳答案
与其继承包装的迭代器类型,我认为只存储三个迭代器( begin
、 end
和 current
)并实现特定迭代器所需的方法会容易得多绑定(bind)检查(递增、递减)并仅委托(delegate)给包装的 current
迭代其他人。
如您所见,您实际上并没有使用容器类型,也没有使用它的迭代器,因此您甚至可以将迭代器类型传递给您的模板类。
template < typename T, typename Iter >
class bound_checked_iterator {
public:
bound_checked_iterator(Iter begin, Iter end)
: begin_(begin), end_(end), current_(begin) {}
// implements the different methods
bound_checked_iterator operator++();
bound_checked_iterator operator--();
bound_checked_iterator operator++(int);
bound_checked_iterator operator--(int);
T& operator *();
const T& operator *() const;
bool operator ==(bound_checked_operator const& other) const;
bool operator !=(bound_checked_operator const& other) const;
private:
Iter begin_, end_, current_;
};
您需要为迭代器实现的方法是:
- 前增量和后增量
- 递减前和递减后
- 解引用运算符
- 平等与不平等比较
您可以获得完整列表here .
作为@Jarod42评论中提到,你甚至不需要将数据类型传递给模板,但你可以使用 std::iterator_traits<Iter>
推断它:
template < typename Iter >
class bound_checked_iterator {
public:
bound_checked_iterator(Iter begin, Iter end)
: begin_(begin), end_(end), current_(begin) {}
// ...
typename std::iterator_traits<Iter>::reference operator*();
// ...
};
关于c++ - 带范围检查的自制迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20809103/