【发布时间】:2019-12-06 00:59:17
【问题描述】:
我通过从非常基本的 std::iterator 模板类继承来为我的自定义容器类实现了一个(非常量)随机访问迭代器(见下文)。执行此操作所需要做的就是传入所需的类型。
我找不到太多关于如何设置反向迭代器的信息,但我很确定有一种方法可以使用现有的迭代器和一些新的 typedef 并定义 rbegin() 和 rend( )。这就是我卡住的地方。有人可以帮忙吗?
template <class T, class A = std::allocator<T>>
class ring {
public:
typedef ring<T, A> self_type;
typedef T value_type;
typedef A alloc_type;
typedef ptrdiff_t size_type;
typedef typename alloc_type::difference_type difference_type;
typedef typename alloc_type::pointer pointer;
typedef typename alloc_type::reference reference;
typedef typename alloc_type::const_pointer const_pointer;
typedef typename alloc_type::const_reference const_reference;
class iterator; // we implement iterator as nested class, so no need to typedef it
iterator begin() { return iterator(this, 0); }
iterator end() { return iterator(this, size()); } // the current size (which is one past the end of the array)
class iterator : public std::iterator<std::random_access_iterator_tag, value_type, difference_type, pointer, reference> {
private:
self_type *ring_; // typedefs defined in ring class apply here
size_type offset_;
public:
iterator(self_type *r, size_type o) : ring_{r}, offset_{o} {}
reference operator* () const { return (*ring_)[offset_]; }
pointer operator-> () const { return &(operator*()); }
iterator& operator++ () {
++offset_;
return *this;
}
friend bool operator== (const iterator& it1, const iterator& it2) { return ((it1.ring_ == it2.ring_ && it1.offset_ == it2.offset_)); }
friend bool operator!= (const iterator& it1, const iterator& it2) { return (!(it1 == it2)); }
iterator& operator-- () {
--offset_;
return *this;
}
iterator operator++ (int) {
iterator clone(*this); // make a duplicate
++offset_;
return clone; // return the duplicate
}
iterator operator-- (int) { // has to be return by value
iterator clone(*this);
--offset_;
return clone;
}
iterator& operator+=(size_type n) {
offset_ += n;
return *this;
}
iterator& operator-=(size_type n) {
offset_ -= n;
return *this;
}
...
reference operator[] (size_type n) const { return (*ring_)[n]; }
};
};
【问题讨论】:
-
你熟悉
std::reverse_iterator吗?无论如何,您需要自己实现rbegin()和rend()。 -
iterator类模板在 C++17 中已弃用,因为它容易出错。 -
是的,我听说这是一种已弃用的方法。最佳做法替代方案是什么?
-
@sid 自己声明类型。或者推出您自己的版本。 (顺便说一句,它是一个类模板,而不是一个方法。)