繁体   English   中英

Iterator和const_iterator运算符++ post和prefix

[英]Iterator and const_iterator operator++ post and prefix

我们正在开发一个自定义List类。 我们正在尝试实现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;
  }

Testcode(带后缀的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重置为其原始值(就好像没有发生增量)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM