简体   繁体   English

Iterator和const_iterator运算符++ post和prefix

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

We are working on a custom List class. 我们正在开发一个自定义List类。 We are trying to implement iterator and const_iterator and its functions but we have a problem with our ++operators. 我们正在尝试实现iterator和const_iterator及其函数,但我们的++运算符存在问题。 PostFix doesn't work at all, and PreFix gives us segfault when we step too far (the current code is a workaround that just returns the last valid result). PostFix根本不起作用,当我们走得太远时,PreFix会给我们带来段错误(当前代码是一个只返回最后一个有效结果的解决方法)。 Question1: How can we fix the segfault related to prefix without returning last valid element? 问题1:如何在不返回最后一个有效元素的情况下修复与前缀相关的段错误? (we have tried returning nullptr). (我们尝试过返回nullptr)。

Postfix just wont iterate, even though we have followed every guide on the internet <.< Postfix只是不会迭代,即使我们已经按照互联网上的每个指南<。<

Question2: Why doesn't PostFix work? 问题2:PostFix为什么不工作?

Code for post&prefix: 帖子和前缀代码:

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 with postfix): 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;

Output for postfix: 后缀输出:

val: 324
val2: 324
val3: 324

Output for prefix: 前缀输出:

val: 2
val2: 3
val3: 3  <-- This is where we segfault if we don't use the controll.

Try with just : 试试吧:

clst++;

instead of : 代替 :

clst = clst++;

The latter resets clst to its original value (as if the increment didn't happen). 后者将clst重置为其原始值(就好像没有发生增量)。

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

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