简体   繁体   中英

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+=() .

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

But I don't know why ?

Well a forward iterator can only be advanced forward one unit at a time. += is generally used to go more than one unit at a time.

wouldn't this operator advance the "forward" iterator like operator++() ?

It would but you could use it like iterator += 10 which would leave you to believe it is going to advance 10 places instantly. Instead it would have to be 10 separate ++ calls.

Isn't there helper function std::advance() that does the same thing ?

Yes there is but it explicitly states that it is multiple ++ calls unless you are using a random iterator.

I'm implementing my own forward list (for learning) and I want to know what's wrong with operator+=()

Your iterator should conform to the standard definition of a forward iterator.

But I don't know why ?

There is certain contract that different category iterators must follow. Description can be found here You can see what contract is for ForwardIterator category, where std::forward_list<T>::iterator belongs to, and there is no r += n operation which is for RandomAccessIterator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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