c++iteratorforward-list

Why doesn't forward iterator have addition assignment operator?


I know std::forward_list<T>::iterator doesn't have a compound-assignment operator (operator+=). But why is that?

I'm asking this for three reasons:

  1. wouldn't this operator advance the "forward" iterator like operator++() ?
  2. Isn't there a helper function std::advance() that does the same thing ?
  3. I'm implementing my own forward list (for learning) and I want to know what's wrong with operator+=().

Solution

  • Use:

    std::advance(it, n);
    

    (Declared in <iterator>.)

    The point is that compound-assignment operators are only provided when the operation has O(1) cost. Since incrementing a forward iterator has linear cost, it's better to make this explicit.

    If you want a new value that's the result of repeated increments, use:

    auto it2 = std::next(it1, n);