我们正在开发自定义列表类。我们正在尝试实现 iterator 和 const_iterator 及其函数,但我们的++ 运算符存在问题。 PostFix 根本不起作用,而当我们走得太远时,PreFix 会给出段错误(当前代码是一种仅返回最后有效结果的变通方法)。 问题1:我们如何在不返回最后一个有效元素的情况下修复与前缀相关的段错误? (我们已经尝试返回 nullptr)。
Postfix 只是不会迭代,即使我们已经遵循了互联网上的所有指南<.<
问题 2:为什么 PostFix 不起作用?
后缀代码:
List_const_iterator_& operator++()
{
if(ptr->next_ != nullptr)
{
ptr = ptr->next_;
return *this;
}
else
return *this;
}
List_const_iterator_ operator++(int unused)
{
List_const_iterator_ temp(*this);
if(ptr->next_ != nullptr)
{
ptr = ptr->next_;
return temp;
}
else
return *this;
}
测试代码(带后缀的atm):
List<int> list1 {324, 2, 3};
List_const_iterator_<int> clst = list1.cbegin();
clst = clst++;
cout << "val: " << clst.ptr->data_ << endl;
clst = clst++;
cout << "val2: " << clst.ptr->data_ << endl;
clst = clst++;
cout << "val3: " << clst.ptr->data_ << endl;
后缀的输出:
val: 324
val2: 324
val3: 324
前缀的输出:
val: 2
val2: 3
val3: 3 <-- This is where we segfault if we don't use the controll.
最佳答案
试试 :
clst++;
代替:
clst = clst++;
后者将 clst
重置为其原始值(就好像增量没有发生一样)。
关于c++ - 迭代器和 const_iterator operator++ post and prefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983680/