Question

We are working on a custom List class. We are trying to implement iterator and const_iterator and its functions but we have a problem with our ++operators. 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). Question1: How can we fix the segfault related to prefix without returning last valid element? (we have tried returning nullptr).

Postfix just wont iterate, even though we have followed every guide on the internet <.<

Question2: Why doesn't PostFix work?

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):

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.
Was it helpful?

Solution

Try with just :

clst++;

instead of :

clst = clst++;

The latter resets clst to its original value (as if the increment didn't happen).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top