前几天我想尝试为向量编写自己的迭代器,当然,这是最原始的例子,因为 c++ 标准中有很多令人困惑的代码。因此,正向向量的常用迭代器工作正常,但反向迭代器存在问题。我将它完全建立在基本迭代器上,只是我专门为反向迭代器更改/反转了运算符。
template<typename Vector>
class VectorRevIterator : public VectorIterator<Vector> //This is normal (work) vector iterator
{
public:
using Base = VectorIterator<Vector>;
VectorRevIterator(PointerType ptr) noexcept : Base(ptr) {};
VectorRevIterator(const VectorRevIterator& other) : Base(other) { *this = other; };
VectorRevIterator& operator++()
{
Base::operator--(); //--ptr;
return *this;
}
VectorRevIterator operator++(int)
{
VectorRevIterator itr = *this;
Base::operator--(); //--*this;
return itr;
}
VectorRevIterator& operator--()
{
Base::operator++(); //++ptr;
return *this;
}
VectorRevIterator operator--(int)
{
VectorRevIterator itr = *this;
Base::operator++(); //++*this;
return itr;
}
VectorRevIterator& operator+=(const PointerType otherPtr)
{
Base::operator-=(otherPtr); //ptr -= otherPtr;
return *this;
}
VectorRevIterator operator+(const PointerType otherPtr)
{
VectorRevIterator itr = *this;
Base::operator-(otherPtr); // itr -= otherPtr
return *this;
}
VectorRevIterator& operator-=(const PointerType otherPtr) { return Base::operator+=(otherPtr); }
VectorRevIterator operator-(const PointerType otherPtr) { Base::operator+(otherPtr); }
ReferenceType operator*() const { return *ptr; }
PointerType operator->() const { return std::_Const_cast(Base::operator->()); }
};
从 Vector 访问迭代器:
template<typename T>
class Vector
{
public:
using ValueType = T;
using PointerType = ValueType*;
using ReferenceType = ValueType&;
using ReverseIterator = VectorRevIterator<Vector<T>>;
public:
T* data;
size_t size;
size_t capacity;
...
// construct/destructor
// custom allocator
// index operators
...
ReverseIterator rBegin() { return ReverseIterator(data + size); }
ReverseIterator rEnd() { return ReverseIterator(data); }
};
问题本身在于,当我尝试以相反的方向遍历所有元素时VectorRevIterator
。当试图将所有这些输出到控制台时,它似乎将一个元素向前移动并且看不到/无法读取第一个元素的字符。但是然后输出所有元素,只有没有最后一个。
这里有一个例子:
Vector<String> values;
values.emplaceBack("1");
values.emplaceBack("2");
values.emplaceBack("3");
values.emplaceBack("4");
values.emplaceBack("5");
Vector<String>::ReverseIterator revIt = values.rBegin();
// output with spdlog
for (revIt; revIt != values.rEnd(); ++revIt)
INFO(*revIt); // error on first iteration, but print only 1, 2, 3, 4
// ouput with std::cout
for (revIt; revIt != values.rEnd(); ++revIt)
std::cout << *revIt << std::endl; // doesn't print anything
如何解决这个问题?要制作反向迭代器,只需还原运算符++
--
+=
-=
和rBegin
rEnd
函数。或者也许我忘记了什么?