【发布时间】:2017-02-21 23:09:29
【问题描述】:
当我运行以下命令时,我错过了列表中的最后一个数据并获取了以前的数据。当我添加一个计数器并尝试减去 1 时,我崩溃了。对此的任何帮助将不胜感激。
template <typename T>
Iterator<T> Iterator<T>::operator--()
{
ptr = ptr->backward;
return *this;
}
template <typename T>
Iterator<T> DoublyLinkedList<T>::end() const
{
Iterator<T> iObj;
iObj.ptr = this->last;
iObj.capacity = this->count;
return iObj;
}
int main() {
DoublyLinkedList<int> *d = new DoublyLinkedList<int>;
for (int i = 2; i <= 20; i += 2) {
d->insertLast(i);
}
//Get an Iterator which points at the end of the list
Iterator<int> iter = d->end();
--iter;
//Test that it does point to the first
checkTest("testIteratorsDecrement #1", 20, *iter);
//Test that our Iterator can move forward;
--iter;
checkTest("testIteratorsDecrement #2", 18, *iter);
//move it some more
for (int i = 0; i < 7; i++) {
--iter;
}
checkTest("testIteratorsDecrement #3", 4, *iter);
--iter;
checkTest("testIteratorsDecrement #4", 2, *iter);
delete d;
return 0;
}
我尝试通过执行以下操作来修复它,但它崩溃了。 count 是一个受保护的 int。
template <typename T>
Iterator<T> DoublyLinkedList<T>::end() const
{
Iterator<T> iObj;
iObj.ptr = this->last + (count -1);
iObj.capacity = this->count;
return iObj;
}
【问题讨论】:
-
this->last - 1,你为什么要在最后一项的地址上加上count?
-
是什么让你觉得它差了一个?
end,按照惯例,代表一个结束,也许这就是你所看到的。更重要的是,我们需要一个可重现的示例来使用(我们可以编译的东西) -
我添加了更多代码,但不知何故我在列表中输出了错误的链接 1。我希望添加一个计数器能让我在最后更进一步。
标签: c++ templates pointers math iterator